Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 703
Sam B. Avatar asked Mar 02 '17 11:03

Sam B.


2 Answers

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);
like image 165
NullDev Avatar answered Nov 12 '22 09:11

NullDev


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)
like image 20
G0dsquad Avatar answered Nov 12 '22 10:11

G0dsquad