Regular expression Ignore duplicate matches

I have a line like this:

var str = "When Home is on fire go and dance in fire"

I want the words homeandfire

For this, I used this Regex:

var words = str.match(/(home)|(fire)/ig)

and the output is as follows:

["Home", "fire", "fire"]

As you can see fire, matching twice, I want to ignore duplicate matches and show only once.

Thanks for the help.

+4
source share
1 answer

You can use this regular expression with a negative lookahead to make sure that it matches the desired word only if the same word no longer exists in the text, which corresponds to the last occurrence of the search words:

/(home|fire)(?!.*\1)/ig

Output:

["Home", "fire"]

RegEx Demo

+4
source

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


All Articles