下面的代码是用来将链接放在单词中的,但它只适用于一个单词,我希望它可以使用两个或更多单词
示例:
"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| ]"+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>
更新:
我不确定这部分是否有效,但我希望你不要更改 script
、img
和 class="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| ]"+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/