gpt4 book ai didi

javascript - 使用javascript自动链接页面上的短语

转载 作者:可可西里 更新时间:2023-11-01 13:20:16 25 4
gpt4 key购买 nike

下面的代码是用来将链接放在单词中的,但它只适用于一个单词,我希望它可以使用两个或更多单词

示例:

"contact us": "www.example.com/contact.html",
"need help": "www.example.com/help.html",
"quick-thinking": "www.example.com/quick.html",

代码:

document.addEventListener("DOMContentLoaded", function(){
var links = {
"contact": "www.example.com/contact.html",
"help": "www.example.com/help.html",
}

var bodi = document.querySelectorAll("body *:not(script)");
for(var x=0; x<bodi.length; x++){
var html = bodi[x].innerHTML;
for(var i in links){
var re = new RegExp("([\\s|&nbsp;]"+i+"(?:(?=[,<.\\s])))", "gi");
var matches = html.match(re);
if(matches){
matches = html.match(re)[0].trim();
html = html.replace(re, function(a){
return ' <a href="'+links[i]+'">'+a.match(/[A-zÀ-ú]+/)[0].trim()+'</a>';
});
}
}
bodi[x].innerHTML = html;
}
});
<div>
Please contact us if you need help
</div>

更新:

我不确定这部分是否有效,但我希望你不要更改 scriptimgclass="thisclass".thisclass:

document.querySelectorAll("body *:not(script)")

最佳答案

你只是替换错了。

a.match(/[A-zÀ-ú]...

需要允许一个空格字符

a.match(/[A-zÀ-ú\s]...

见下文:

document.addEventListener("DOMContentLoaded", function(){
var links = {
"contact us": "www.example.com/contact.html",
"need help": "www.example.com/help.html",
"hyphen-spaced-word" : "www.example.com/help.html"
}

var bodi = document.querySelectorAll("body *:not(script)");
for(var x=0; x<bodi.length; x++){
var html = bodi[x].innerHTML;
for(var i in links){
var re = new RegExp("([\\s|&nbsp;]"+i+"(?:(?=[,<.\\s])))", "gi");
var matches = html.match(re);
//console.log(matches);
if(matches){
matches = html.match(re)[0].trim();
html = html.replace(re, function(a){
return ' <a href="'+links[i]+'">'+a.match(/[A-zÀ-ú\s-]+/)[0].trim()+'</a>';
});
}
}
bodi[x].innerHTML = html;
}
});
<div>
Please contact us if you need help. See hyphen-spaced-word.
</div>

关于javascript - 使用javascript自动链接页面上的短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51468285/

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