I have the following situation, I'm searching in a HTML string the attributes.
I have the following regex wich works alright but I want to get just unique results, of course I can apply some filter to the results array but I think this is achieveable with pure regex.
https://regex101.com/r/UqCuJS/1
So in this situation class is returned twice, but I only want 1 time:
['class', 'data-text']
not ['class', 'data-text', 'class']
const html = `<div class="foo">
<span data-text="Some string" class="bar"></span>
</div>`
console.log(html.match(/[\w-:]+(?=\s*=\s*".*?")/g))
http://jsbin.com/bekibanisa/edit?js,console
You can pass result of .match()
to Set
, which does not allow duplicate values. If necessary convert Set
instance back to Array
.
const html = `<div class="foo">
<span data-text="Some string" class="bar"></span>
</div>`
// or use existing `RegExp`
console.log([...new Set(html.match(/([\w-]+)(?=[=]")/g))])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With