Escaping numerals in string.replace

2019-09-19 12:21发布

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?

1条回答
放荡不羁爱自由
2楼-- · 2019-09-19 12:58

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 than 10 groups available. See below snippet for an example of this.

const regex = /(\w+)/g;
const str = `something`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, '$10');

console.log('Substitution result: ', result);

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.

const regex = /(\w+)((((((((()))))))))/g;
const str = `something`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, '$10');

console.log('Substitution result: ', result);

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.

const regex = /(\w+)((((((((()))))))))/g;
const str = `something`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, function(a, b) {
  return b+'0';
});

console.log('Substitution result: ', result);

查看更多
登录 后发表回答