Bernie
Bernie

Reputation: 5055

Modify regex matches inside the replacement string

I've a problem with some regex to grab url's from a text and modify all matches inside the replacement string again by a function. The code below is a dummy example of what I want do to. Is something like this possible?

var exp = /\b((http:\/\/|https:\/\/)[\S]*)/g;
text = text.replace(exp, "<a href=\"$1\" title=\""+parseUri("$1").host+"\"></a>");

Upvotes: 0

Views: 105

Answers (1)

nhahtdh
nhahtdh

Reputation: 56809

Supply a function as 2nd argument to .replace:

var exp = /\bhttps?:\/\/[\S]*/g;
text = text.replace(exp, function ($0) {
    return '<a href="' + $0 + '" title="' + parseUri($0).host + '"></a>'
});

(Note that $0 is just a variable name, you can name it differently).

Check String.replace's documentation on MDN for the meaning of the arguments to the replacement function. The first argument is the text capture by the whole regex. Then the next N arguments are the text captured by the N capturing groups in the regex.

I also take my liberty to rewrite the regex. Since \b is an assertion, no text will be consumed.

Upvotes: 1

Related Questions