0

i am trying to replace all references to a keyword or number in a string to something else, i am able to do this using the following, but need the /g to make sure it changes all references. However i want to make it dynamic, change the first number to a varible, and then put that varible inbetween the forward slash but it wont work.

works

var res = str.replace(/5026555042451/g, "34234324");

doesnt work

var customstring = "5026555042451";
var res = str.replace(/+customstring+/g, "34234324");

2 Answers2

5

You should create a new RegExp object

Basically, it's an object that take 2 arguments : the rule and the flag.

In the end, it look like that :

var customstring = "5026555042451";
var res = str.replace(new RegExp(customstring, 'g'), "34234324");

That is also the way you concatenate strings in a regular expression. For more information, see How can I concatenate regex literals in JavaScript?

Community
  • 1
  • 1
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
2
var res = str.replace(/+customstring+/g, "34234324");

and then put that varible inbetween the forward slash but it wont work.

This is because /whatever/ is not string but regular expression literal and there are no slashes in it. Slashes are just delimiters (like apostrophes and quote-marks in strings: var s = 'whatever' but regular expression itself is inside these. This is why you can't add anything to slashes: they just aren't here. You just put plus sign in regular expression which has its own meaning (you can use plus sign to catch characters or groups that occur one or more times, e.g. /a+/ matches aa in poaalpopop).

PS. @Karl-André Gagnon there is a typo in your answer: new RegExp, not New RegExp ;)

hex13
  • 500
  • 5
  • 11