Reputation: 301
I would like to parse the following text into formatted URLs with anchor tags:
something is wrong with http://www.gbin1.com/index.html, but cannot find the reason in http://www.google.com
How can I replace the text URLs above with <a href="url">url</a>
and also shorten it using JavaScript as displayed below:
something is wrong with <a href="http://www.gbin1.com/index.html">gbin1.com</a>, but cannot find the reason in <a href="http://www.gbin1.com">google.com</a>
Upvotes: 0
Views: 783
Reputation: 1244
Check this solution.
var x = "something is wrong with http://www.gbin1.com/index.html, but cannot find the reason in http://www.google.com";
var expression = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var split = x.split(" ");
for(var i=0; i< split.length; i++){
if(split[i].match(regex)){
var text = split[i].split(".").slice(1).join(".").split("/")[0];
split[i] = '<a href=\"' +split[i]+'\">'+text+'</a>';
}
}
console.log(split.join(" "));
Upvotes: 2