0

I struggle to find a solution for what is probably pretty simple, and despite I crawl a lot of questions, I can't manage to make it work.

Here are 2 HTML elements:

<a href="#content1" class="buttonDelete" style="color:white">Test1</a>
<a href="#content2" onclick="confirmDelete('test');" class="buttonDelete" style="color:white">Test2</a>

I want to get ONLY the content of the 1st element's href property (#content1). It must match because the html element contains no "onclick" property.

This regex works for matching the 1st element only:

^<a href="#"((?!onclick).)*$

but I can't figure out how to get the HREF content. I've tried this:

^<a href="#(.*)"((?!onclick).)*$

but in this case, both elements are matching.

Thanks for your help !

wewereweb
  • 197
  • 1
  • 10

2 Answers2

0

I strongly suggest that you should do that in two steps. For one thing, parsing arbitrary html with a regexp is a notoriously slippery and winding road. For the other: there is no achievement in doing everything with one illegible regex.

And there's more to it: "contains no "onclick" attribute" is not the same as "href attribute is not directly followed by onclick attribute". So, a one-regex-solution would be either very complicated or very fragile (html tags have arbitrary attributes order).

var a = [
    '<a href="#content1" class="buttonDelete" style="color:white">Test1</a>',
    '<a href="#content2" onclick="confirmDelete(\'test\');" class="buttonDelete" style="color:white">Test2</a>'
];

console.log(
    a.filter(i => i.match(/onclick/i) == null)
     .map(i => i.match(/href="([^"]+)"/i)[1]
)

This assumes that your href attribute values are valid and do not contain quotes (which is, of course, technically possible).

Michael Antipin
  • 3,522
  • 17
  • 32
0

Regex is not made for this. JavaScript would work better. This code will store an array of the hrefs matching your requirements in the variable hrefArray.

var hrefArray = [];
for (var elem of document.getElementsByTagName('a')) {
  if (elem.onclick) hrefArray.push(elem.href)
}

An example with your HTML is in the snippet below:

var hrefArray = [];
for (var elem of document.getElementsByTagName('a')) {
  if (elem.onclick) hrefArray.push(elem.href)
}

console.log(hrefArray);
body {
  background-color: gray;
}
<a href="#content1" class="buttonDelete" style="color:white">Test1</a>
<a href="#content2" onclick="confirmDelete('test');" class="buttonDelete" style="color:white">Test2</a>
Skylar
  • 928
  • 5
  • 18