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
1 Answer
Reset to default 6You 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
版权声明:本文标题:javascript - Regular Expression Ignore duplicate matches - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744627907a2616367.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论