Hi, how can i exclude the $1 from the replace rule?
regex = new RegExp('hallo, test, blub', 'gi');
content = content.replace(regex,'<strong>$1</strong>');
alert('$1'); // dont work
Thanks in advance! Peter
Hi, how can i exclude the $1 from the replace rule?
regex = new RegExp('hallo, test, blub', 'gi');
content = content.replace(regex,'<strong>$1</strong>');
alert('$1'); // dont work
Thanks in advance! Peter
$1 refers to the first group captured by the regex and is available only in the replacement string.
For example, if content is The score is 234 and the regex is score is (\d+), it will be replaced as <strong>234</strong>.
If you want the value, you can use content.match(regex)[1].
var c = "asd 123";
var r = /[a-z]+\s+(\d+)/;
var match = c.match(r);
if(match)
console.log(match[1]);
else
console.log("no match");
$1 only applies in the second argument to replace() and doesn't exist outside of that line of code. If you strictly need to get your hands on the match string, you could however do something like:
var dollar1;
content = content.replace(regex, function(s, p1) {
dollar1 = p1;
return '<strong>' + p1 + '</strong>';
});
alert(dollar1);