如何在javaScript数组中找到以某些字母开头的所有元素 [英] How can I find all the elements in javaScript array that start with certain letter

查看:854
本文介绍了如何在javaScript数组中找到以某些字母开头的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方法可以只过滤出以字母a开头的数组中的项目.即

Is there any way to do this filtering out only items in an array that start with the letter a. ie

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

推荐答案

在检查之前,您必须trim item中的空格.

You have to trim the spaces from the item before checking.

正则表达式以检查是否以^a

Regex to check if start with: ^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);

这篇关于如何在javaScript数组中找到以某些字母开头的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆