Reputation: 132
At the moment, I have the following regex for replacing a URL to a HTML hyperlink:
msg = msg.replace(/(\b((https?|ftp|file):\/\/|www.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi, "<a href='out.php?u=$1'>$1</a>");
This replaces
http://www.stackoverflow.com
into
<a href='out.php?u=http://www.stackoverflow.com'>http://www.stackoverflow.com</a>
But now I have a problem. When I already have a hyperlink, I don't want to replace the URL inside that hyperlink to a new hyperlink.
So:
<a href='http://www.stackoverflow.com'>Stackoverflow</a>
must not become:
<a href='<a href='out.php?u=http://www.stackoverflow.com'>http://www.stackoverflow.com</a>'>Stackoverflow</a>
Does somebody know how I can prevent this?
Upvotes: 1
Views: 333
Reputation: 132
I've already fixed it by adding a white space before and after the string, and replaces all URLs with a whitespace before and after:
msg = " " + msg + " ";
msg = msg.replace(/(\s)(((https?|ftp|file):\/\/|www.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])(\s)/gi, " <a target='_blank' href=\"" + websiteUrl + "/out.php?u=$2\"><font color='" + hyperlinkColor + "'>$2</font></a> ");
msg = StringUtil.trim(msg);
This doesn't replace all the hyperlinks, because a hyperlink doesn't have whitespaces before and after the URL.
Upvotes: 2
Reputation: 3218
You can do that with a negative look-ahead assert, written as (?!expression). So...
?!(\<a)/(\b((https?|ftp|file):\/\/|www.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi, "<a href='out.php?u=$1'>$1</a>");
Upvotes: 1