I have a piece of code that uses matching groups in regular expressions to manipulate a string.
something = mystring.replace(someRegexObject, '$1' + someotherstring);
This code works fine in most cases however I encounter a problem when the someotherstring
has a numeric value... then it gets concatenated with $1 messing up the group matching.
Is there an easy way for me to escape the contents of someotherstring
to separate it from the matching group?
Issue Explained
The question isn't the clearest, but I think I understand your issue.
Using regex in JavaScript, you can, in fact, use
$10
as a substitute for capture group 1 if - and only if - there are less than10
groups available. See below snippet for an example of this.Unfortunately, I believe you have a regex that captures more than
X
(10
if you're looking at the example above). See it return an incorrect value in the snippet below.Solution
In order to fix this, you'll have to change your Javascript code to implement a function in the place of the substitution string as the following snippet demonstrates.