<html>
<body>
<h1>My First Heading</h1>
<p>Lorem ipsum dolor sit amet, <a href=”www.test1.com”>consectetur adipiscing
elit</a>, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco <a
href=”www.test1.com/go/green”>laboris</a> nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est <a href=”
www.test1.com/go/red”>laborum.</a></p>
</body>
</html>
我正在努力编写一个jvascript代码,在执行时它会在页面上找到包含'/ go /'的所有链接,并在其中添加'-aw'文本,因此它们看起来像这样:
•www.test1.com/go/green-aw
•www.test1.com/go/red-aw
<script>
function myFunction() {
?????????
?????????
?????????
}
</script>
有人可以帮忙吗?
答案 0 :(得分:1)
此处未调用RegEx。 querySelectorAll
支持在属性中进行搜索:
function myFunction() {
document.querySelectorAll('a[href*="/go/"]').forEach(a => a.href += '-aw');
}
答案 1 :(得分:0)
像这样使用。只需forEach
。然后使用href
正则表达式验证go
包含/\/go\//
文字
document.querySelectorAll('a').forEach(function(a){
a.href =a.href.match(/\/go\//) ? a.href+'-aw' : a.href;
console.log(a.href)
})
<h1>My First Heading</h1>
<p>Lorem ipsum dolor sit amet, <a href="www.test1.com">consectetur adipiscing
elit</a>, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco <a href="www.test1.com/go/green">laboris</a> nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est <a href="www.test1.com/go/red">laborum.</a></p>