[英]Find all the substrings in string with regex javascript
我有一個富文本編輯器,它會生成包含超鏈接的輸出。 例如<p><a href="test.com" target="_blank">Link1</a> fsdfsdf <a href="google.com" target="_blank">Link2</a> 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.