Regex matches unique results

I have the following situation: I'm looking for attributes in an HTML string.

I have the following regular expression that works well, but I want to get only unique results, of course, I can apply some filter to the array of results, but I think this is achieved with a pure regular expression.

https://regex101.com/r/UqCuJS/1

So, in this situation, the class returns twice, but I want only 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))
Run codeHide result

http://jsbin.com/bekibanisa/edit?js,console

+4
source share
2 answers

.match() Set, . , Set 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))])
Hide result
+3

'/g'

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

Source: https://habr.com/ru/post/1676026/


All Articles