Skip to content Skip to sidebar Skip to footer

Js: Find Urls In Text, Make Links

What would be the following PHP code rewritten in JS be, so that url links inside of text blobs could be replaced with html links? I've started a jsfiddle.

Solution 1:

Use this:

var text = "The text you want to filter goes here. http://google.com";
text = text.replace(
    /((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/g,
    '<a href="$1">$1</a>'
);

Explanation:

The g here is a global flag; it will replace all urls.

I also added an capture group for the entire expression, so I could use the backreference $1.

Post a Comment for "Js: Find Urls In Text, Make Links"