//js
var content ="welcome http://www.yahoo.com?career hi http://www.yahoo.com http://www.yahoo.com http://10.179.105.223:81/Person.aspx?accountname=MHC%5CAdministrator ";
//******************************************************************************//
//data coming from server
var distinctURLs = ["http://www.yahoo.com?career" , "http://www.yahoo.com" , "http://www.yahoo.com" , "http://10.179.105.223:81/Person.aspx?accountname=MHC%5CAdministrator" ];
//******************************************************************************//
//replacing with anchor tag
for (var j = 0; j < distinctURLs.length; j++) {
content = content.replace(new RegExp( distinctURLs[j], 'g' ), "<a href='" + distinctURLs[j] + "'>" + distinctURLs[j] + "</a>");
}因此,在上面的情况下,我首先从var content中找到urls并用<a>标记替换,但是它不能正常工作。
//output should be
welcome <a href="http://www.yahoo.com?career">http://www.yahoo.com?career</a> hi <a href="http://www.yahoo.com">http://www.yahoo.com</a > <a href="http://www.yahoo.com">http://www.yahoo.com</a> <a href="http://10.179.105.223:81/Person.aspx?accountname=MHC%5CAdministrator">http://10.179.105.223:81/Person.aspx?accountname=MHC%5CAdministrator</a>使用replace和new RegExp没有得到预期的结果
在这里你可以参考代码
提前谢谢!
发布于 2015-09-09 05:34:24
您可以使用regex使用替换()来做这样简单的事情。
var content ="welcome http://www.yahoo.com?career hi http://www.yahoo.com http://www.yahoo.com http://10.179.105.223:81/Person.aspx?accountname=MHC%5CAdministrator ";
document.write(content.replace(/http:\/\/[^\s]+/g,'<a href="$&">$&</a>'))
更新:
或者用您的代码可以完成
var content = "welcome http://www.yahoo.com?career hi http://www.yahoo.com http://www.yahoo.com http://10.179.105.223:81/Person.aspx?accountname=MHC%5CAdministrator ";
var distinctURLs = ["http://www.yahoo.com?career", "http://www.yahoo.com", "http://www.yahoo.com", "http://10.179.105.223:81/Person.aspx?accountname=MHC%5CAdministrator"];
document.write(content.split(/\s+/).map(function(v) {
return distinctURLs.indexOf(v) == -1 ? v : '<a href="' + v + '">' + v + '</a>';
}).join(' '));https://stackoverflow.com/questions/32471548
复制相似问题