JS: find urls in text, make links
What would the following PHP code be, rewritten in JS so that url links inside text blocks can be replaced with html links? I started jsfiddle .
<?php
// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";
// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {
// make the urls hyper links
echo preg_replace($reg_exUrl, "<a href="{$url[0]}">{$url[0]}</a> ", $text);
} else {
// if no urls in the text just return the text
echo $text;
}
?>
+2
source to share
1 answer
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:
g
here is a global flag; it will replace all urls.
I also added a capture group for the whole expression, so I could use backreference $1
.
+3
source to share