Ruan Mendes
Ruan Mendes

Reputation: 92274

How to turn urls padded by space into links

I have the following code that is used to turn http URLs in text into anchor tags. It's looking for anything starting with http, surrounded by white space (or the beginning/end of input)

function linkify (str) {
    var regex = /(^|\s)(https?:\/\/\S+)($|\s)/ig;
    return str.replace(regex,'$1<a href="$2" target="_blank">$2</a>$3')
}

// This works
linkify("Go to http://www.google.com and http://yahoo.com");

// This doesn't, yahoo.com doesn't become a link
linkify("Go to http://www.google.com http://yahoo.com");

The case where it doesn't work is if I only have a single space between two links. I'm assuming it's because the space in between the two links can't be used to match both URLs, after the first match, the space after the URL has already been consumed.

To play with: http://jsfiddle.net/NgMw8/

Can somebody suggest a regex way of doing this? I could scan the string myself, looking for a regex way of doing it (or some way that doesn't require scanning the string my self and building a new string on my own.

Upvotes: 0

Views: 489

Answers (3)

Stphane
Stphane

Reputation: 3456

None will work if there are any html element stuck to the url ...

Similar question and it's answers HERE

Some solutions can handle url like "test.com/anothertest?get=letsgo" and append http://

  • Workaround may be done to handle https and miscellaneous tld ...

Upvotes: 0

Just use a positive lookahead when matching your final $|\s, like so:

var regex = /(^|\s)(https?:\/\/\S+)(?=($|\s))/ig;

Upvotes: 1

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91299

Don't capture the final \s. This way, the second url will match the preceding \s, as required:

function linkify (str) {
    var regex = /(^|\s)(https?:\/\/\S+)/ig;
    return str.replace(regex,'$1<a href="$2" target="_blank">$2</a>')
}

http://jsfiddle.net/NgMw8/3/

Upvotes: 2

Related Questions