最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Regular Expression Ignore duplicate matches - Stack Overflow

programmeradmin4浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论