如何在JavaScript数组中找到以特定字母开头的所有元素

3

有没有办法仅过滤出以字母a开头的数组项。例如:

var fruit = 'apple, orange, apricot'.split(',');
  fruit = $.grep(fruit, function(item, index) {
  return item.indexOf('^a'); 
  });
alert(fruit);

在jQuery中尝试这个:var $beginswitha = $(":input[name^='a']")。然后将该变量放入您的indexOf语句中。 - Callum.
3个回答

3
三件事情:
·你需要以', '为分割符进行拆分,而不是',' ·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); 
}));

2

在检查之前,您需要从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);

太棒了。非常感谢。我很菜鸟,所以非常感激。 - user2678132

1
您可以这样使用 charAt

var fruit = 'apple, orange, apricot'.split(', ');
  fruit = $.grep(fruit, function(item, index) {
  return item.charAt(0) === 'a';
});
alert(fruit);

太棒了。感谢你的帮助。 - user2678132

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接