繁体   English   中英

使用正则表达式javascript查找字符串中的所有子字符串

[英]Find all the substrings in string with regex javascript

我有一个富文本编辑器,它会生成包含超链接的输出。 例如<p><a href="test.com" target="_blank">Link1</a>&nbsp;fsdfsdf <a href="google.com" target="_blank">Link2</a>&nbsp;fsdffsdfs</p>我需要在其中获取所有<a>标记和href ,以便我可以运行验证(例如,如果它是外部链接),以便可以添加nofollow标记等。我应该使用哪种正则表达式正在使用? 也许除了正则表达式以外的其他东西?

谢谢。

需要在其中获取所有标签和hrefs

也许除了正则表达式以外的其他东西?

尝试创建元素来设置编辑文本作为.innerHTML ,使用.map()返回的数组a元素href属性值

// editor text
var html = document.querySelector("#editor").textContent,
    // element to store `html` from editor
    div = document.createElement("div"),
    // set `div` `.innerHTML` to editor text
    div.innerHTML = html;
// `links` : all `a` elements ; `list` : `links` `href` values
var links = [].slice.call(div.querySelectorAll("a")),
    list = links.map(function(el) {
      return el.href
    });
// filter `list`, set `rel="nofollow"` attribute at `a` element
// within `links` where condition at `if` returns `true`
for (var i = 0; i < list.length; i++) {
   if (/* condition ; for example if it's an external link */) {
     links[i].setAttribute("rel", "nofollow")
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM