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"
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With