Anderson
Anderson

Reputation: 341

regex match unique results

I have the following situation, I'm searching in a HTML string for the attributes.

I have the following regex which 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 achievable 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

Upvotes: 5

Views: 4520

Answers (2)

guest271314
guest271314

Reputation: 1

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))])

Upvotes: 10

Jed
Jed

Reputation: 10887

Try removing the '/g' global modifier

console.log(html.match(/[\w-:]+(?=\s*=\s*".*?")/))

Upvotes: -1

Related Questions