0

I want to replace the "3" into "5". When it is using static it's working fine but when I use it through variable var allvar= '"3"'; it's not working fine.

Here is the jsfiddle link

Amadan
  • 191,408
  • 23
  • 240
  • 301
Ws Memon
  • 107
  • 7
  • 3
    The question is really unclear. If you just want to replace 3 into 5, you can just use string.replace(new RegExp('3', 'g'), '5'). – Chit Khine Nov 21 '19 at 10:43
  • 2
    Indeed. Also, please don't add unnecessary tags. This question has nothing to do with [tag:jquery], [tag:jquery-ui], [tag:jquery-mobile] or [tag:javascript-objects]. – Amadan Nov 21 '19 at 10:44
  • https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string see the link for your help and reference – Chit Khine Nov 21 '19 at 10:46
  • Ok dear @Amadan – Ws Memon Nov 21 '19 at 10:46

1 Answers1

4

new RegExp( /[allvar]+/g ); will construct a regular expression matching all uninterrupted sequences of one or more characters from the set a, l, v, a, r.

To construct a regular expression from a variable, you can do this:

new RegExp(allvar, 'g')

It would also be good to escape characters with special meaning to RegExp, unless you intend for allvar to contain regexp source. Unfortunately, RegExp.escape is still not in the language, so one would use a workaround.

new RegExp(escapeRegExp(allvar), 'g')
Amadan
  • 191,408
  • 23
  • 240
  • 301