简体   繁体   English

用javascript中的另一个字符串替换

[英]replace one string with another in javascript

How can I replace parts of one string with another in javascript? 如何在javascript中用一个字符串替换另一个字符串? No jQuery. 没有jQuery。

For example if I wanted to replace all spaces (" ") is "The quick brown fox jumped over the lazy dog". 例如,如果我要替换所有空格(“”)为“快速的棕色狐狸跳过了懒狗”。 with plus ("+"). 加号(“ +”)。

I'm looking for something like PHP's str_replace and that hopefully doesn't involved regex. 我正在寻找类似PHP的str_replace的东西,希望它不涉及正则表达式。

Javascripts very own String.prototype.replace() MDN method to the rescue. Javascript拥有自己的String.prototype.replace() MDN方法来进行救援。

"The quick brown fox jumped over the lazy dog".replace( /\s+/g, '+' );

Be aware that .replace() will not modify an existing string in place, but will return a new string value. 请注意, .replace()不会修改现有的字符串,但会返回新的字符串值。


If you for some reason don't want to have any RegExp involved, you have to do the dirty work yourself, for instance 如果您由于某种原因不想参与任何RegExp ,则必须自己做一些肮脏的工作,例如

var foo = 'The quick brown fox jumped over the lazy dog';

foo.split( '' ).map(function( letter ) {
    return letter === ' ' ? '+' : letter;
}).join('');

But you would have to check for any kind of white-space character here, to be on-level with the RegExp solution. 但是您必须在这里检查任何种类的空格字符,才能与RegExp解决方案保持一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM