tags:

views:

89

answers:

4

Hello, when I try the following it doesn't work: str.replace("| stuff", "")

But if I remove the PIPE it does? str.replace("stuff", "")

Why doesn't the JS function allow for the PIPE | ? What can I do to do a replace that includes a pipe?

+1  A: 

Because .replace accepts a RegExp, and | is a special character in RegExp. You need to escape it.

For example, use str.replace(/\|/g, "") to remove every | character.

KennyTM
Thanks but I want to replace the following String " | stuff" There will just be one pipe, how can I replace both?
AnApprentice
a regexp was not used in the example in the question, so no need to escape it
peller
+3  A: 

No, it should be working, unless you use /| stuff/ or RegExp("| stuff") instead of "| stuff"

"xyz| stuff".replace("| stuff", ""); //returns xyz
S.Mark
+1 You are absolutely right. I should have tested before answering.
Doug Neiner
it doesn't work....
AnApprentice
In which browser?
S.Mark
@S.Mark, just tested it and it works in IE6+, Firefox 2.0+, Chrome and Safari.
Doug Neiner
+1  A: 

Isn't it

"xyz| stuff".replace("\| stuff", ""); //returns xyz
Jourkey
that backslash has no effect
peller
+1  A: 

str.replace("| stuff", "") should work but will only replace the first occurrence. If you want to replace all of them, try a using a regex like str.replace(/\|\sstuff/g, "")

Tim Goodman
Or just `str.replace(/\| stuff/g, "")`, but the `\s` makes it work for any whitespace character
Tim Goodman
+1 - great - thanks!
adrianos