Search code examples
javascriptregexbackreference

Accessing $1 etc. outside of string.replace() in javascript regex?


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?


Solution

  • 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.