0

So I've been playing around with the replace function (method?) in js.

$get('msgBar').replace(/+/g,' ');

Let's say the content of $get('msgBar') is "Welcome+back+now".

replace('+',' ') would only replace the first +, and not the second.

replace(/+/g,' ') crashes

replace(/"+"/g,' ') and replace(/\+/g,' ') are both the same as the first

I'm sure the solution is easy... :)

1 Answer 1

6

You must quote +:

$get('msgBar').replace(/\+/g,' ');

'+' is a meta character, like '*'. It means "one more repetitions". It you literally want '+' , then you have to quote it with the backslash.

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

10 Comments

Specifically, you must quote it because '+' has meaning in regular expressions, and the first argument to replace is used as a regex, not a bare string for comparison...
Unfortunately, I've already tried that (as in the original post), and it didn't work for whatever reason... that is, only the first + is replaced.
No you didn't. You forgot the 'g' - it means "global match" and instructs regex to find and replace all matches.
T'was a typo. I copied and pasted your solution and it did not work. Sorry.
@Luther's answer works for me. Edit: On second thought, -deletes my answer-
|

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.