monxas
monxas

Reputation: 2637

unable to test regex in javascript

I'm pretty unfamiliar with RegExp, and Im trying to implement it to detect urls in strings. The one regexp I want to use is this one (please don't provide your own):

/(((http|ftp|https)://)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?)/g

And replace all the matches with this:

<a href="$1">$1</a>

If you visit http://gskinner.com/RegExr/ with that example and use it in the replace, you'll see it works flawlessly, but it's impossible to build a working solution with this in javascript.

var text = "hi, demo link http://stackoverflow.com is a great website"
//regexp magic


//expected result:
textWithLink ="hi, demo link <a href="http://stackoverflow.com">http://stackoverflow.com</a> is a great website"

Upvotes: 1

Views: 103

Answers (3)

Seimen
Seimen

Reputation: 7250

var str = 'hi, demo link http://stackoverflow.com is a great website',
    regex = /(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?)/g;
str.replace(regex, '<a href="$1">$1</a>');

Note: It's your exact regex, I just escaped the forward slashes.

Upvotes: 2

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146390

The RegExp literal you provide is invalid:

/(((http|ftp|https)://)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:/~+#-]*[\w@?^=%&amp;/~+#-])?)/g
^                   ^^
Start               |\__ Error
                    |
                   End

It works in the link you provide because that application strips delimiters automatically and inadvertently fixes the error.

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

You can do this

var ok = /(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:/~+#-]*[\w@?^=%&amp;/~+#-])?)/.test(str);

to test if a string is an URL.

If you want to look for URLs in a string, use

var matches = str.match(/(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:/~+#-]*[\w@?^=%&amp;/~+#-])?)/g);

Note that it's a regex literal and that I had to escape the /.

Upvotes: 1

Related Questions