user2837849
user2837849

Reputation: 337

How to globally replace pipe symbol "|" in string

How can I globally replace the | (pipe) symbol 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-"

Upvotes: 18

Views: 30227

Answers (5)

Philipp
Philipp

Reputation: 11361

Another solution is, to do a substring replacement instead of a regex to replace the pipe character. However, the String.prototype.replace() method will only replace the first substring instance, like here:

"so|me|str|ing".replace("|", "-"); // "so-me|str|ing" → WRONG

Possible workarounds:

  1. Split the string into an array and join it with the new delimiter:
"so|me|str|ing".split("|").join("-"); // "so-me-str-ing" → RIGHT
  1. Use a loop to replace one substring after the other.
var str = "so|me|str|ing"; 
while(str.indexOf("|") >= 0) {
  str = str.replace("|", "-"); // "so-me|str|ing" → RIGHT
}

Use .replaceAll()

Use the modern approach String.prototype.replaceAll() -- beware, that this method is only supported by a few browsers yet:

"so|me|str|ing".replaceAll("|", "-"); // "so-me-str-ing" → RIGHT

Upvotes: 0

Devdatta Tengshe
Devdatta Tengshe

Reputation: 4075

In my case, the pipe was coming as an variable, so I couldn't use any of these solutions. Instead, You can use:

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

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

//should be 'Foo-bar- Test'

Upvotes: 0

ChadF
ChadF

Reputation: 1758

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

This is a great resource for working with RegEx: https://www.regex101.com/

Upvotes: 6

squill25
squill25

Reputation: 1208

| means OR, so you have to escape it like this: \|

Upvotes: 9

joews
joews

Reputation: 30330

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

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

Upvotes: 34

Related Questions