Reputation: 941
I have a rich text editor and it produces output which includes hyperlinks as well. For example <p><a href="test.com" target="_blank">Link1</a> fsdfsdf <a href="google.com" target="_blank">Link2</a> fsdffsdfs</p>
I need to get all the <a>
tags and href
s in them so that I can run a validation for example if it's an external link, so that i can add nofollow
tag etc. What kind of regex should I be using? Or anything other than regex maybe?
Thanks.
Upvotes: 0
Views: 64
Reputation: 1
need to get all the tags and hrefs in them
Or anything other than regex maybe?
Try creating an element to set editor text as .innerHTML
, use .map()
to return array of a
element href
attribute values
// 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")
}
}
Upvotes: 1