1

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
  • what is str, what is your result, and what are you trying to achieve? Commented Jan 20, 2010 at 6:03

4 Answers 4

5

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.

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

2 Comments

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

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

"xyz| stuff".replace("| stuff", ""); //returns xyz

2 Comments

+1 You are absolutely right. I should have tested before answering.
@S.Mark, just tested it and it works in IE6+, Firefox 2.0+, Chrome and Safari.
1

Isn't it

"xyz| stuff".replace("\| stuff", ""); //returns xyz

Comments

1

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, "")

1 Comment

Or just str.replace(/\| stuff/g, ""), but the \s makes it work for any whitespace character

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.