0

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.

2
  • 1
    First of all, \\( and \\) must be used in the template string literal used as a regex pattern. To match up to the ), you may use [^)]*. What does replace hold? Commented Sep 5, 2017 at 12:14
  • This solved the problem I don't need to worry about the rest of the string if I can just match the parenthesis directly. Commented Sep 5, 2017 at 12:19

2 Answers 2

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.