0

I have to select link tag (a) with a specific data-attr. Now I'm doing it this way: /<a.*?data-extra-url=".*?<\/a>/g. But... For some reason when my input string is without any line br -> it results in a totally wrong selection, for example:

<div> <br> <a data-some-id="3-6-9;id-1-2-3" data-more-id="1-3-5" data-extra-url="https://somehost.api/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" href="https://somehost.api/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" class="some-class">someDuplicateHere1</a></div> wysiwyg<br> <div><a class="popup-wrap-id-1-2-3" href="https://somehost.api/app/id-1-2-3?someparam=sub-id-1-2-3;sub-sub-id-1-2-3">firstImage</a></div> <br> <div>somecontent</div> <div> <span> <div><a data-some-id="456;789" href="https://somehost.api/app/id-4-5-6?someparam=sub-id-4-5-6;sub-sub-1-2-3">second</a></div> <br> </span> also some more content </div> <div> <span> <div><a data-some-id="3-6-9;id-1-2-3" data-more-id="1-3-5" data-extra-url="https://somehost.api/app/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" href="https://somehost.api/app/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" class="some-class">someDuplicateHere</a></div> rtf<br> </span> <br> </div> </div>

and a live example: https://regex101.com/r/JkI3Fu/1

for some reasons in my selection there are all links, what I do wrong?

As a result I want to get:

array = ['<a data-some-id="3-6-9;id-1-2-3" data-more-id="1-3-5" data-extra-url="https://somehost.api/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" href="https://somehost.api/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" class="some-class">someDuplicateHere1</a>', '<a data-some-id="3-6-9;id-1-2-3" data-more-id="1-3-5" data-extra-url="https://somehost.api/app/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" href="https://somehost.api/app/sub-id-1-2-3?someparam=3-6-9;id-1-2-3" class="some-class">someDuplicateHere</a>']
like here: https://regex101.com/r/NiFFXd/1
brabertaser19
  • 5,678
  • 16
  • 78
  • 184

2 Answers2

1

It is important that your regex looks at what you don't want in your match. Use ^ like this

<a[^>]*data-extra-url="[^>]*>[^>]*.

It should solve your problem

AnJo
  • 74
  • 6
0

You can use

document.querySelectorAll('a[data-extra-url]');

The [attribute] selector is used to select elements with a specified attribute.

From CSS Attribute Selectors

Raz Luvaton
  • 3,166
  • 4
  • 21
  • 36