admin管理员组

文章数量:1323342

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?

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?

Share Improve this question edited Jan 20, 2010 at 5:59 peller 4,54320 silver badges21 bronze badges asked Jan 20, 2010 at 5:39 AnApprenticeAnApprentice 111k202 gold badges637 silver badges1k bronze badges 1
  • what is str, what is your result, and what are you trying to achieve? – peller Commented Jan 20, 2010 at 6:03
Add a ment  | 

4 Answers 4

Reset to default 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.

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

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

Isn't it

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

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

本文标签: JavaScript Replace String with a Character Stack Overflow