views:

41

answers:

1

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... :)

+6  A: 

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.

Luther Blissett
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...
Tetsujin no Oni
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.
Julian H. Lam
No you didn't. You forgot the 'g' - it means "global match" and instructs regex to find and replace **all** matches.
Luther Blissett
T'was a typo. I copied and pasted your solution and it did not work. Sorry.
Julian H. Lam
@Luther's answer works for me. *Edit:* On second thought, -deletes my answer-
BoltClock
@Julian it definitely works. You must have some other problem; post more of your code.
Pointy
... yep, it works. My apologies.I was editing the wrong block of code. Fail.
Julian H. Lam
Pointy - $get's pretty cool, actually. It's a mootools extension written by Jens Anders Bakke.Take a look: http://webfreak.no/wp/2007/09/05/get-for-mootools-a-way-to-read-get-variables-with-javascript-in-mootools/
Julian H. Lam
@Julian - MooTools provides string extensions to deal with [querystrings](http://mootools.net/docs/more/Native/String.QueryString#String:parseQueryString). You could parse the querystring as `location.search.substr(1).parseQueryString().msgBar`. Looks a little verbose, but a wrapper function like `$get` is easy to write for the above.
Anurag
Thanks, Anurag - looks great! That might be a better solution to use in conjunction with $get
Julian H. Lam