How to globally replace the pipe symbol "|" in line

How to globally replace a character |(pipe) in a string? When I try to replace it with "so|me|str|ing".replace(/|/g, '-'), I get"-s-o-|-m-e-|-s-t-r-|-i-n-g-"

+8
source share
4 answers

|has special meaning ( A|Bmeans "match A or B"), so you need to avoid it:

"so|me|str|ing".replace(/\|/g, '-');
+22
source

|means OR, therefore, you need to escape as follows:\|

+7
source

"so | me | str | ing".replace(/[|]/g, '-')

RegEx: https://www.regex101.com/

+4

, . :

let output_delimiter  ='|';
let str= 'Foo|bar| Test';

str.replace(new RegExp('[' + output_delimiter + ']', 'g'), '-')

//should be 'Foo-bar- Test'
0

All Articles