0

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?

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
qadenza
  • 9,025
  • 18
  • 73
  • 126

4 Answers4

1

You can escape the asterisk sign - \*:

var str = '****'
var result = str.replace(/\*/g, "bar")

console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

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);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
1

Just for fun.

Split string by * and then join with bar

var str = '****'
var result = str.split("*").join('bar')

console.log(result)
Muhammad Usman
  • 10,039
  • 22
  • 39
0

Just escape the * char with \*, like str.replace(/\*/g, "bar")

Karen Grigoryan
  • 5,234
  • 2
  • 21
  • 35