繁体   English   中英

如何在javaScript数组中找到以某些字母开头的所有元素

[英]How can I find all the elements in javaScript array that start with certain letter

有什么方法可以执行此操作,仅过滤出以字母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); 
}));

你要trim从空间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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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