0

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>");

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.