test_replace_link
by ning wang
HTML
<div id="output"></div>
JavaScript
function getLinkObject(text) {
var linkTemplate = text;
//regex pattern for http(s)
var urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/ig;
var matchedLinks = text.match(urlRegex);
if(!matchedLinks)
return null;
matchedLinks.forEach(function(item, index){
linkTemplate = linkTemplate.replace(item, "{"+index+"}");
});
return {
linkTemplate: linkTemplate,
matchedLinks: matchedLinks
};
}
String.prototype.format=function(args) {
var str = this, default_regex = new RegExp("{[0-9]+}", "g");
return str.replace(default_regex, function(item){
var intVal = parseInt(item.substring(1,item.length-1));
var replace = "";
if(intVal >= 0){
replace = args[intVal];
}
console.log(replace);
return replace;
});
};
var news = `John Brennan has been an outspoken critic of the president.
He called Donald Trump(http://classic.us) treasonous over his meeting with the Russian leader in Helsinki; he's called him imbecilic; and a danger to the US.(https://wwww.baidu.com)
Now Donald Trump has had his revenge, revoking the former CIA chief's security clearance - and threatening a number of other national intelligence officials - all of whom have one thing in common: they've also been critical of the president.
But in justifying this move there's been no suggestion that Mr Brennan either leaked classified material or sought to make money from it.`;
var testOutput = getLinkObject(news);
var outHtml = testOutput.linkTemplate.format(["<a href='http://classic.us'>http://classic.us</a>","<a...