Skip to content Skip to sidebar Skip to footer

Regex To Find Urls In A String

I'm using a regex to find URLs in a string, and then turn them into real HTML links, (in JavaScript). The problem with my regex is that it includes the previous character before ht

Solution 1:

The problem is that JavaScript will always replace the full match, not an inner capture group.

So here is a neat (and tested) trick to alleviate this. Make your first subpattern capturing:

/([^\]\/">]|^)((https?):\/\/[-A-ZÅÄÖ0-9+&@#\/%?=~_|!:,.;]*[-A-ZÅÄÖ0-9+&@#\/%=~_|])/ig

And then include it explicitly:

'$1<ahref="$2">$2</a>'

Solution 2:

Use a look behind:

 /(?<[^\]\/">]|^)((https?):\/\/[-A-ZÅÄÖ0-9+&@#\/%?=~_|!:,.;]*[-A-ZÅÄÖ0-9+&@#\/%=~_|])/ig 

Post a Comment for "Regex To Find Urls In A String"