作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
//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
的网址并替换为 <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
它没有得到预期的结果
这里你可以引用Code
提前致谢!
最佳答案
您可以使用 replace()
做这样简单的事情 使用正则表达式
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(' '));
关于javascript - 如何将字符串中的 url 替换为 anchor 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32471548/
我是一名优秀的程序员,十分优秀!