I have this for replace all instances of foo
with bar
.
str.replace(/foo/g, "bar")
What if I need to replace all instances of *
character:
str.replace(/*/g, "bar")
Javascript /*
sees as comment starting.
How to solve this?
I have this for replace all instances of foo
with bar
.
str.replace(/foo/g, "bar")
What if I need to replace all instances of *
character:
str.replace(/*/g, "bar")
Javascript /*
sees as comment starting.
How to solve this?
You can escape the asterisk sign - \*
:
var str = '****'
var result = str.replace(/\*/g, "bar")
console.log(result)
You need to escape *
:
str.replace(/\*/g, "")
A *
is a special character in a regular expression that matches the previous token zero or more times. To use it literally in a regular expression it must be escaped.
Demo:
let str = 'lorem ip*sum do*lor sit am*et';
let result = str.replace(/\*/g, "");
console.log(result);
Just for fun.
Split string by *
and then join with bar
var str = '****'
var result = str.split("*").join('bar')
console.log(result)