有没有办法仅过滤出以字母a开头的数组项。例如:
var fruit = 'apple, orange, apricot'.split(',');
fruit = $.grep(fruit, function(item, index) {
return item.indexOf('^a');
});
alert(fruit);
有没有办法仅过滤出以字母a开头的数组项。例如:
var fruit = 'apple, orange, apricot'.split(',');
fruit = $.grep(fruit, function(item, index) {
return item.indexOf('^a');
});
alert(fruit);
', '
为分割符进行拆分,而不是','
·indexOf
方法不能使用正则表达式参数,只能使用字符串参数。如果要使用正则表达式,请使用search
方法。indexOf
(和search
)返回的是查找到目标词汇的索引位置,你需要将这个位置与你的期望值==0
进行比较。或者你可以使用正则表达式的test
方法,它会返回一个布尔值。alert('apple, orange, apricot'.split(', ').filter(function(item, index) {
return item.indexOf('a') == 0;
}));
alert('apple, orange, apricot'.split(', ').filter(function(item, index) {
return /^a/.test(item);
}));
在检查之前,您需要从item
中删除空格。
用正则表达式检查是否以^a
开头:
var fruit = 'apple, orange, apricot'.split(',');
fruit = $.grep(fruit, function (item, index) {
return item.trim().match(/^a/);
});
alert(fruit);
其他解决方案:
var fruits = [];
$.each(fruit, function (i, v) {
if (v.match(/^a/)) {
fruits.push(v);
}
});
alert(fruits);
charAt
:
var fruit = 'apple, orange, apricot'.split(', ');
fruit = $.grep(fruit, function(item, index) {
return item.charAt(0) === 'a';
});
alert(fruit);
var $beginswitha = $(":input[name^='a']")
。然后将该变量放入您的indexOf语句中。 - Callum.