What is wrong in this fiddle.
这个小提琴有什么不对。
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?
我能够匹配第一个地址对象和最后一个地址对象,但我无法匹配第二个地址对象。但是第二个也有相同的单词。知道为什么吗?
1 个解决方案
#1
1
Just use .indexOf()
只需使用.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/
演示:http://jsfiddle.net/RPdx4/4/
OK, Regex just
好的,正则表达式
var pattern = RegExp('\\b' + city + '\\b')
var pattern = RegExp('\\ b'+ city +'\\ b')
or
var pattern = RegExp("\\b("+ city +")")
var pattern = RegExp(“\\ b(”+ city +“)”)
Demo : http://jsfiddle.net/RPdx4/5/
演示:http://jsfiddle.net/RPdx4/5/
#1
1
Just use .indexOf()
只需使用.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/
演示:http://jsfiddle.net/RPdx4/4/
OK, Regex just
好的,正则表达式
var pattern = RegExp('\\b' + city + '\\b')
var pattern = RegExp('\\ b'+ city +'\\ b')
or
var pattern = RegExp("\\b("+ city +")")
var pattern = RegExp(“\\ b(”+ city +“)”)
Demo : http://jsfiddle.net/RPdx4/5/
演示:http://jsfiddle.net/RPdx4/5/