Jordash
Jordash

Reputation: 3093

Regular Expression to replace variable with variable

I have some string that looks like this:

var string = popupLink(25, 'Any string')

I need to use a regular expression to change the number inside (note that this is a string inside of a larger string so I can't simply match and replace the number, it needs to match the full pattern, this is what I have so far:

var re = new RegExp(`popupLink\(${replace},\)`, 'g');
var replacement = `popupLink(${formFieldInsert.insertId},)`;
string = string.replace(re, replacement);

I can't figure out how to do the wildcard that will maintain the 'Any String' part inside of the Regular Expression.

Upvotes: 0

Views: 50

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

If you just need to change the number, just change the number:

string = string.replace(/popupLink\(\d+/, "popupLink(" + replacement);

Example:

var str = "var string = popupLink(25, 'Any string')";
var replacement = 42;
str = str.replace(/popupLink\(\d+/, "popupLink(" + replacement);
console.log(str);

If you really do have to match the full pattern, and "Any String" can literally be any string, it's much, much more work because you have to allow for quoted quotes, ) within quotes, etc. I don't think just a single JavaScript regex can do it, because of the nesting.

If we could assume no ) within the "Any String", then it's easy; we just look for a span of any character other than ) after the number:

str = str.replace(/(popupLink\()\d+([^)]*\))/, "$1" + replacement + "$2");

Example:

var str = "var string = popupLink(25, 'Any string')";
var replacement = 42;
str = str.replace(/(popupLink\()\d+([^)]*\))/, "$1" + replacement + "$2");
console.log(str);

Upvotes: 1

Jerodev
Jerodev

Reputation: 33186

If you are looking for a number, you should use \d. This will match all numbers. For any string, you can use lazy searching (.*?), this will match any character until the next character is found.

In your replacement, you can use $1 to use the value of the first group between ( and ), so you don't lose the 'any string' value.

Now, you can simply do the following:

var newNumber = 15;
var newString = "var string = popupLink(25, 'Any string')".replace(/popupLink\(\d+, '(.*?)'\)/, "popupLink(" + newNumber + ", '$1')");
console.log(newString);

Upvotes: 1

Related Questions