AnApprentice
AnApprentice

Reputation: 111070

JavaScript Replace String with a Character |

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?

Upvotes: 1

Views: 3316

Answers (4)

YOU
YOU

Reputation: 123907

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

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

Upvotes: 3

Tim Goodman
Tim Goodman

Reputation: 23976

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

Upvotes: 1

Jourkey
Jourkey

Reputation: 34986

Isn't it

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

Upvotes: 1

kennytm
kennytm

Reputation: 523704

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.

Upvotes: 5

Related Questions