0

As we all know $1 and so on are backreferences to captured groups in a string.replace() when using a regex, so you can do something like:

string.replace(/(http:\/\/\S*)/g, '<a href="$1" target="_blank">link<\/a>')

Now my question is whether there is a way to access the captured data in $1 and so on OUTSIDE the replace. Like backrefarray[1] for $1 or something...

Is such thing possible and how?

Wingblade
  • 9,585
  • 10
  • 35
  • 48

3 Answers3

2

Yes, you can use match :

var array = str.match(/(http:\/\/\S*)/g);

(but the array starts at index 0)

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

You can use a function for replacement instead of a fixed string:

string.replace(/(http:\/\/\S*)/g, function() {
    return '<a href="'+arguments[1]+'" target="_blank">link<\/a>';
})

The matches of the whole pattern and of each group are passed as arguments to the function.

Gumbo
  • 643,351
  • 109
  • 780
  • 844
1

RegExp.$1

Also, after any regexp operation is finished, the $1, $2 capture variables, (if they exist), are available globally as properties of the global RegExp object. Try this out after a successful match:

alert(RegExp.$1);
ridgerunner
  • 33,777
  • 5
  • 57
  • 69