Reputation: 483
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?
Upvotes: 4
Views: 5992
Reputation: 9
You have to escape special characters like "|" with a backslash. Try replacing your last line with this:
console.log(mystring.replace(/\|/g , ","));
I tested the above in Chrome and it looks to do what you're trying to do.
See the following regarding Special Characters for more details on when and how to escape special characters:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Upvotes: 0
Reputation: 26
Pipe symbol is a special charcter. you have to use escape charcter.
console.log(mystring.replace(/\|/g , ","));
Upvotes: 0
Reputation: 476659
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 , ","));
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|
Upvotes: 5
Reputation: 26444
Pipe characters must be escaped
var mystring = "this|is|a|test"
console.log(mystring.replace(/\|/g, ","));
Upvotes: 1
Reputation: 136
|
is a special character, and needs to be escaped with \
var mystring = "this|is|a|test";
console.log(mystring.replace(/\|/g , ","));
Upvotes: 1
Reputation: 47
You just need to escape the |
,so if you need this,is,a,test,you need to do
console.log(mystring.replace(/\|/g , ","));
Upvotes: 1
Reputation: 36599
Escape |
character.
var mystring = "this|is|a|test"
console.log(mystring.replace(/\|/g, ","));
Upvotes: 10