简体   繁体   中英

Regex matching one word but not matching another

What is wrong in this fiddle.

http://jsfiddle.net/RPdx4/

 function getMatches(data,city){
             var matchArr = [];
             var pattern = new RegExp("\\b("+ city +")","gi");
        for (var i in data){        
                 var searchStr = data[i].searchstr;
                 if(pattern.test(searchStr)){
                    matchArr.push(data[i]);
                }
            }
            return matchArr;
        }

I am able to match the first address object and and the last address object but i am not able to match the second one.But the second one also has the same word. Any idea why?

Just use .indexOf()

 function getMatches(data,city){
        var matchArr = [];
        for (var i in data){        
                 var searchStr = data[i].searchstr;
                 var index = searchStr.indexOf(city);
                if(index!==-1) {
                    matchArr.push(data[i]);
                }
            }
            return matchArr;
        }

var arr = getMatches(x,'Dar es');
alert("arr: " + arr.length);

Demo : http://jsfiddle.net/RPdx4/4/


OK, Regex just

var pattern = RegExp('\\\\b' + city + '\\\\b')

or

var pattern = RegExp("\\\\b("+ city +")")

Demo : http://jsfiddle.net/RPdx4/5/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM