admin管理员组

文章数量:1388877

I have string like this :

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

I want check my string have words home and fire

For doing this i used this Regex :

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

and the output like this :

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

As you can see fire matched twice , i want Ignore duplicate matches and only show for once.

Thanks for Helping.

I have string like this :

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

I want check my string have words home and fire

For doing this i used this Regex :

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

and the output like this :

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

As you can see fire matched twice , i want Ignore duplicate matches and only show for once.

Thanks for Helping.

Share Improve this question asked Sep 3, 2015 at 12:08 user1086010user1086010 6971 gold badge10 silver badges25 bronze badges 2
  • Do you need to return true if both words exist in the string? Then use /\bhome\b.*\bfire\b|\bfire\b.*\bhome\b/i.test(s). Or /^(?=.*\bhome\b)(?=.*\bfire\b)/i.test(s). – Wiktor Stribiżew Commented Sep 3, 2015 at 12:14
  • @AruneshSingh when i remove g flag output is like this ["Home", "Home", undefined] its not working – user1086010 Commented Sep 3, 2015 at 12:20
Add a ment  | 

1 Answer 1

Reset to default 6

You can use this negative lookahead based regex to make sure to match desired word only if same word doesn't exist further in text thus matching last occurrence of the search words:

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

Output:

["Home", "fire"]

RegEx Demo

本文标签: javascriptRegular Expression Ignore duplicate matchesStack Overflow