0

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.

3
  • 2
    What's wrong with regex? Commented Jun 18, 2013 at 13:58
  • @MattBurland I've learned or been taught that its best to not use regex when you don't have to. Commented Jun 18, 2013 at 14:23
  • Well that's a silly attitude. You should learn how and when to use them instead of believing some silly restriction. Commented Jun 18, 2013 at 14:30

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.