Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex match unique results

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

like image 809
Anderson Avatar asked Apr 30 '17 15:04

Anderson


1 Answers

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))])
like image 190
guest271314 Avatar answered Oct 05 '22 10:10

guest271314