Reputation: 2637
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
Reputation: 7250
var str = 'hi, demo link http://stackoverflow.com is a great website',
regex = /(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?)/g;
str.replace(regex, '<a href="$1">$1</a>');
Note: It's your exact regex, I just escaped the forward slashes.
Upvotes: 2
Reputation: 146390
The RegExp literal you provide is invalid:
/(((http|ftp|https)://)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?)/g
^ ^^
Start |\__ Error
|
End
It works in the link you provide because that application strips delimiters automatically and inadvertently fixes the error.
Upvotes: 1
Reputation: 382102
You can do this
var ok = /(((http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?)/.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.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?)/g);
Note that it's a regex literal and that I had to escape the /
.
Upvotes: 1