Nigel Gossage
Nigel Gossage

Reputation: 95

Regex to match urls using JavaScript

I'm using this regex which so far has been pretty good...

var r = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;

But if I have a string such as the following...

 '<div>http://www.a-random-site.com/page1-blah-blah</div>Another bit of text'

Then the bit that is matched would be...

http://www.a-random-site.com/page1-blah-blah</div>Another

How can I alter the regex to take into account that an angled bracked could terminate a link?

Upvotes: 0

Views: 119

Answers (2)

Saram
Saram

Reputation: 1510

I do not know if there is easy way to fix your regexp. I just use this code for url:

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

Source link

Working example

Upvotes: 0

mohsen dorparasti
mohsen dorparasti

Reputation: 8415

I edited saram's regex pattern and tested it by Expresso and it worked with your sample :

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

Upvotes: 1

Related Questions