gpt4 book ai didi

javascript - 如何将字符串中的 url 替换为 anchor 标记

转载 作者:行者123 更新时间:2023-11-28 15:18:42 25 4
gpt4 key购买 nike

//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>

使用replacenew 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>'))

<强> Regex explanation

更新:

或者用你的代码你可以做到

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(' '));
  1. 使用 split() 拆分内容
  2. 迭代使用map()
  3. 使用 indexOf() 检查值是否在数组 distinctURLs并返回所需值
  4. 使用 join() 按空格​​连接数组值

关于javascript - 如何将字符串中的 url 替换为 anchor 标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32471548/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com