Chud37
Chud37

Reputation: 5007

Replacing URLS with Hyperlinks

I found the following function:

function addHyperlinks(str) {
    // Set the regex string
    var regex = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/ig
    // Replace plain text links by hyperlinks
    var replaced_text = str.replace(regex, "<a href='$1' target='_blank'>$1</a>");
    // Echo link
    return replaced_text;
}

Which works okay, however when there is a dash in the URL it stops processing there. So for instance, the following URL:

http://website.com/some-internet-page

Will get replaced with:

<a href='http://website.com/some'>http://website.com/some</a>-internet-page

I'm not good with regex, could anyone help modify the above so that this doesnt happen?

Upvotes: 0

Views: 140

Answers (1)

Chud37
Chud37

Reputation: 5007

@Tonny said it in the comments above:

/(https?://([-\w-.]+)+(:\d+)?(/([\w-/_.]*(\?\S+)?)?)?)/ig

Thank you!

Upvotes: 1

Related Questions