我必须对大量记录进行批量更新,并且这些记录中包含 anchor 标记。我的脚本应该能够将 target = '_blank'
添加到所有 anchor 标记。我需要使用 Javascript 和正则表达式。
到目前为止,我想出了一个可以查找所有 href 属性的正则表达式,但还没有弄清楚如何替换所有标签。
下面的代码片段显示我的正则表达式有效,但我如何确保所有 anchor 标记都被替换?
下面的代码片段只替换了最后一个标签。
function myFunction() {
// get the text to work with
var str = document.getElementById("demo").innerHTML;
//Look for href attribute and add target attribute, to use it as a replacement
var x = /href.*=.*['""].+?['""]/.exec(str) + " target = '_blank'";
// Replace the 1st anchor tag
var res = str.replace(/(href.*=.*['""].+?['""])/, x);
document.getElementById("result").innerHTML = res;
}
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo"><a href = 'link1' > TAG1 </a> , <a href = 'link2' > TAG2 </a> , <a href = 'link3' > TAG3 </a></p>
<p id="result"></p>
<button onclick="myFunction()">Try it</button>
最佳答案
您可以使用它代替您目前拥有的:
var res = str.replace(/href/g, 'target="_blank" href');
这是工作代码:
function myFunction() {
// get the text to work with
var str = document.getElementById("demo").innerHTML;
//Look for href attribute and add target attribute
// Replace on all the anchor tag
var res = str.replace(/href/g, 'target="_blank" href');
document.getElementById("result").innerHTML = res;
}
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>
<p id="demo"><a href='link1'> TAG1 </a> , <a href='link2'> TAG2 </a> , <a href='link3'> TAG3 </a>
</p>
<p id="result"></p>
<button onclick="myFunction()">Try it</button>
关于Javascript 和 RegEx : add an attribute to all anchor tags in a text using regular expression, Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36768409/