Reputation: 1449
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.
Upvotes: 0
Views: 394
Reputation: 235962
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.
Upvotes: 11