0

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>&nbsp;fsdfsdf <a href="google.com" target="_blank">Link2</a>&nbsp;fsdffsdfs</p> I need to get all the <a>tags and hrefs in them so that I can run a validation for example if it's an external link, so that i can add nofollowtag etc. What kind of regex should I be using? Or anything other than regex maybe?

Thanks.

2
  • It depends. Are you editing an HTML text file? Or are you using a JS script on a web page to select certain DOM elements? Commented Jan 4, 2016 at 7:59
  • @jkdev Kind of an HTML text file, no DOM elements are included. I'm using a CMS product and I have text areas for users to enter context. Commented Jan 4, 2016 at 8:06

1 Answer 1

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")
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Keep in mind that this is a text editor, so you'll need to parse that text into the DOM, first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.