Reputation: 23
I run into a problem where the regular expression won't match two similar words:
bitcoin and bitcoin atm
new RegExp("(?:^|\\b)(bitcoin|bitcoin atm|test bitcoin)(?!\\w)");
(function myFunction() {
var str = "bitcoin and bitcoin atm and test and test a and new test";
var patt = new RegExp("(?:^|\\b)(bitcoin|bitcoin atm|test|test a|new test)(?!\\w)", "g");
var res = str.match(patt);
document.getElementById("demo").innerHTML = res;
})()
p{
font-size: 30px;
}
<p id="demo"></p>
Upvotes: 2
Views: 78
Reputation: 1951
Move more specific matches to be higher priority in your matching pattern.
(function myFunction() {
var str = "bitcoin and bitcoin atm and test and test a and new test";
var patterns = ['bitcoin', 'bitcoin atm','test', 'test a', 'new text'];
patterns.sort(function(a,b){return b.length - a.length})
var patt = new RegExp("(?:^|\\b)(" + patterns.join('|') + ")(?!\\w)", "g");
var res = str.match(patt);
document.getElementById("demo").innerHTML = res;
})()
p{
font-size: 30px;
}
<p id="demo"></p>
Upvotes: 3