Hello I need to remove all occurrences of | from a string. This is what I am doing currently
var mystring = "this|is|a|test"
console.log(mystring.replace(/|/g , ","));
This gives me this result: ,t,h,i,s,|,i,s,|,a,|,t,e,s,t, This is not what I want. Why is this not working?
When I try the following, it works for commas.
var mystring = "this,is,a,test"
console.log(mystring.replace(/,/g , ":"));
This gives me ----> this:is:a:test
Why does it not work for OR and how can I fix it?
Escape |
character.
var mystring = "this|is|a|test"
console.log(mystring.replace(/\|/g, ","));
That's because the pipe character (|
) is interpreted as the regex-or.
You can however use the pipe char between square brackets, like [|]
:
var mystring = "this|is|a|test"
console.log(mystring.replace(/[|]/g , ","));
regex101 demo
Square brackets are usually used to write a sequence of characters, but a (positive) side-effect is that most special characters are interpreted literally inside a square bracket environment, as is specified by the regex101 explanation next to the regex:
[|]
match a single character present in the list below
|
the literal character|
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With