4

Possible Duplicate:
How to replace plain URLs with links?

I have several strings that have links in them. For instance:

var str = "I really love this site: http://www.stackoverflow.com" 

and I need to add a link tag to that so the str will be:

I really love this site: <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a> 

I imagine there would be some regex involved, but I can't get it to work for me with match(). Any other ideas

2
  • Simple regular expressions are a naive approach to this problem and will fail a lot of tests for edge cases. When detecting URLs, it's ALWAYS better to rely on a specialized library. Here's why. Commented Feb 21, 2014 at 5:46
  • I created this library that might help anyone looking for a solution in this page: ali-saleem.github.io/anchorme.js Commented Jul 16, 2015 at 19:53

3 Answers 3

10

That's easy:

str.replace( /(http:\/\/[^\s]+)/gi , '<a href="$1">$1</a>' ) 

Output:

I really love this site: <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a> 
Sign up to request clarification or add additional context in comments.

3 Comments

The code above will fail a lot of tests for edge cases. When detecting URLs, it's ALWAYS better to rely on a specialized library. Here's why.
@DanDascalescu I agree
@SeanPatrickFloyd: thank you! BTW/OT: any chance to consider this reopen request and this one? Thank you!
4
function replaceURL(val) { var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; return val.replace(exp,"<a href='$1'>$1</a>"); } 

2 Comments

+1 for the elaborate regex. didn't know js had the \b marker or I would have used it
The code above will fail a lot of tests for edge cases. When detecting URLs, it's ALWAYS better to rely on a specialized library. Here's why.
0

I can think of a quick and dirty Regular Expression based solution. Something on the lines of

RegExp exp = new RegExp('(.*)(http://[^ ])(.*)', 'g'); // matches URLs string = string.replace(exp, $1 + '<a href=\"' + $2 + '\">' + $2 '</a>' + $3); 

I haven't tested it yet though, so needs some refining.

1 Comment

Regular expressions like that will fail a lot of tests for edge cases. When detecting URLs, it's ALWAYS better to rely on a specialized library. Here's why.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.