1

I want to find every url in text and wrap them with a tag (<a href="...">...</a>).

var src = "bla blaaa blaaaaaa 1  http://yahoo.com  text something about and. http://www.google.com";
var match = /http:\/\/([a-z0-9.-]+)/.exec(src); //this only can one matched
// result: ["http://yahoo.com", "yahoo.com"]

But i need to wrap every links.

2 Answers 2

2

You can use /g (global) to match all occurences and the backreference like this:

var src = "bla blaaa blaaaaaa 1  http://yahoo.com  text something about and. http://www.google.com";
var match = src.replace(/http:\/\/([a-z0-9.-]+)/g, '<a href="$1">$1</a>');

You can test it out here.

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

1 Comment

First of all the link is great that i didn't know before. Secondly thank you for /g explanation.
1
var res = src.replace(/(http:\/\/([a-z0-9.-]+))/g, '<a href="$1">$2</a>');

Outputs:

bla blaaa blaaaaaa 1 <a href="http://yahoo.com">yahoo.com</a> text something about and. <a href="http://www.google.com">www.google.com</a>

Not sure that was the intention, but what I could think of. Use <a href="$1">$1</a> as replacement if you want to preserve the http:// prefix in the link text, too.

(In the meantime Nick Craver provided the answer and introduced the g modifier.)

4 Comments

\0 isn't a backreference, you can test it here: jsfiddle.net/nick_craver/9beM2
@Nick Craver Nope, that's what I found out, too :-S Edited. Thanks for noting.
if i use <a href="$1">$2</a> i think it will use first link on second address like <a href="yahoo.com">google.com</a> and all these links don't open the real page because of they don't have http:// do they ?!?
@uzay95 No, the first capturing group ($1) is the first parenthesis (I added those to the pattern), the second ($2) is without the http:// prefix. BTW <a href="www.google.com"> is not a link to google.com but to the relative resource www.google.com!

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.