简体   繁体   中英

replace one string with another in javascript

How can I replace parts of one string with another in javascript? No 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.

Javascripts very own String.prototype.replace() MDN method to the rescue.

"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.


If you for some reason don't want to have any RegExp involved, you have to do the dirty work yourself, for instance

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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