Javascript Remove All '|' in a String [Duplicate]

I've got text from a title that can contain one or more | in it I'd like to use javascript to remove all instances of it.

I've tried

$('title').text().replace(/ |g /, ' ');
"What’s New On Netflix This Weekend: March 3–5 | Lifestyle"
1

Your regex is invalid.

A valid one would look like that:

/\|/g

In normal JS:

var text = "A | normal | text |";
var final = text.replace(/\|/g,"");
console.log(final);

Instead of using .replace() with a RegEx, you could just split the string on each occurence of | and then join it.

Thanks to @sschwei1 for the suggestion!

const text = "A | normal | text |";
let final = text.split("|").join("");
console.log(final);

For more complex replacements, you could also do it with the .filter() function:

var text = "A | normal | text |";

var final = text.split("").filter(function(c){ 
    return c != "|";
}).join("");

console.log(final);

Or with ES6:

const text = "A | normal | text |";
let final = text.split("").filter(c => c !== "|").join("");
console.log(final);

Update: As of ES12 you can now use replaceAll()

const text = "A | normal | text |";
let final = text.replaceAll("|", "");
console.log(final);
2

RegEx was incorrect, it should look like this, with the g switch on the end, and the | escaped.

var str = "What’s New On Netflix |This Weekend: March 3–5 | Lifestyle"

var replaced = str.replace(/\|/g, '');

console.log(replaced)
David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest