tags:

views:

26

answers:

2

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

A: 

$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");
Amarghosh
Thats it! Thanks! -> working example http://www.jsfiddle.net/V9Euk/234/
Peter
In the JS method, you can also specify a function instead of the replacement string. Within that function you can assign the matching string(s) to a variable and use it after the replace (see http://jsfiddle.net/Nzkrk/ for example. I'm not sure when this was introduced to JS and I've never found any documentation on it, but it is supported in every browser I've tested.
Andrew
@Andrew That's required only if you're replacing. If all you want is to get the substring, you needn't use a replace callback for that.
Amarghosh
A: 

$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);
Scott Evernden
Thank you very much!
Peter