Javascript 和 RegEx : add an attribute to all anchor tags in a text using regular expression, Javascript

标签 javascript regex

我必须对大量记录进行批量更新,并且这些记录中包含 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/

相关文章:

javascript - 计算字符串中至少包含一个字母数字字符的单词数

Javascript 匹配和正则表达式

java - 正则表达式解析多行数据

javascript - 正则表达式替换列表中的 0 但不是 10、20、30 等中的 0 - 使用 js 替换

regex - 索引函数中的正则表达式

javascript - 在 PHP 中使用 HTML 标签

javascript - 如何从 GitHub 检索热门用户?

javascript - 在 Google App 脚本中返回多个参数值

javascript - typeahead.js、localStorage 和大型 json 文件

javascript - 根据一行中的元素数调整内容 (100%)