Regex Is Not Capturing Value
Solution 1:
The RegExp.$1-$9
properties are non-standard - as MDN says:
Non-standard
This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
So, it's not surprising that it doesn't work in some implementations.
RegExp
refers to the global regular expression object, which is of course not the same thing as the test you just carried out. If you want to use the results of a match, you should use the .match
method on the string (or exec
on the pattern), and use the indicies of the resulting match object (with bracket notation and numeric indicies):
const input = 'PROBLEM_5_YES_1_';
const match = input.match(/^PROBLEM_(\d+)_YES_(\d+)_$/);
if (match) {
console.log(match[1]);
console.log(match[2]);
}
In Javascript, dollar signs followed by a number only have a meaning in a replacer function, where $1
, for example, will be replaced with the first captured group:
console.log(
'foo bar'.replace(/(foo) (bar)/, '$2 $1')
);
Post a Comment for "Regex Is Not Capturing Value"