3

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.

<?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;

}
?>

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This does not ignore already hyperlinked urls.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.