I have a situation where I have text which contains URL links. The links are in 2 forms
- www.stackoverflow.com
- <a href="http://www.stackoverflow.com">Stack over flow</a>
I am trying to create a simple function that uses regex that will wrap all links of type 1 with A HREF tag but leaving the other ones already wrapped a lone.
I have something like this but not successful.
function replaceURLWithHTMLLinks(text) {
var exp = /(<(\s*)a(\s)*href.*>.*<\/(\s)*a(\s*)>)/ig;
var matches = exp.exec(text);
for(var i=0; i < matches.length; i++) {
var line = matches[i];
if(!exp.test(line)) {
var exp2 = /(\b(?:(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[-A-Z0-9+&@#\/%=~_|$])|”(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[^"\r\n]+”?|’(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[^'\r\n]+’?)/ig;
text = text.replace("http://","");
text = text.replace(exp2, "<a href=http://$1>$1</a>");
}
}
return text;
}
It's not working but hoping someone could fix it :)
EDIT
The solution that fixed it, with the help of @MikeM answer
function replaceLinksSO(text) {
rex = /(<a href=")?(?:https?:\/\/)?(?:(?:www)[-A-Za-z0-9+&@#\/%?=~_|$!:,.;]+\.)+[-A-Za-z0-9+&@#\/%?=~_|$!:,.;]+/ig;
return text.replace(rex, function ( $0, $1 ) {
if(/^https?:\/\/.+/i.test($0)) {
return $1 ? $0: '<a href="'+$0+'">'+$0+'</a>';
}
else {
return $1 ? $0: '<a href="http://'+$0+'">'+$0+'</a>';
}
});
}