Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing pipe in string

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?

like image 344
Avinash Prabhakar Avatar asked Dec 01 '22 12:12

Avinash Prabhakar


2 Answers

Escape | character.

var mystring = "this|is|a|test"
console.log(mystring.replace(/\|/g, ","));
like image 123
Rayon Avatar answered Dec 09 '22 17:12

Rayon


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 |
like image 37
Willem Van Onsem Avatar answered Dec 09 '22 15:12

Willem Van Onsem