-1

I'm attempting to replace a string with another string in Javascript and using the answer given in How do you use a variable in a regular expression? by Eric Wendelin - code is the following:

var re = new RegExp(delim, 'g');
return input.replace(re,","); 

When i run this i get the error

/***/: Nothing to repeat

(the value of delim is "***" btw)

I understand if you get a Nothing to repeat error it means you haven't properly escaped a character in your regexp but why do i get this error in this case ?

Community
  • 1
  • 1
auburg
  • 1,184
  • 1
  • 10
  • 16

1 Answers1

2

* is the reserved repetition character, that matches 0 or more times the previous character or group, so you need to escape it (equivalent to {0,}).

Change the delimeter string to \\*\\*\\* or \\*{3}.

delim = '\\*{3}'
input = 'hello *** world'
var re = new RegExp(delim, 'g');
console.log(input.replace(re, ","))
Uriel
  • 13,905
  • 4
  • 21
  • 43