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

送分小仙女□ 提交于 2020-03-16 06:55:11

问题


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);

回答1:


Three things:

  • You want to split by ', ', not ','
  • indexOf doesn't take a regex, but a string, so your code searches for a literal ^. Use search if you want to use regular expressions.
  • indexOf (and search) do return the index where they find the sought-after term. You'll have to compare that to your expectation: == 0. Alternatively, you can use the regex test method which returns a boolean.

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:


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

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);

Other solution:

var fruits = [];
$.each(fruit, function (i, v) {
    if (v.match(/^a/)) {
        fruits.push(v);
    }
});
alert(fruits);



回答3:


You can use charAt like so :

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


来源:https://stackoverflow.com/questions/30210946/how-can-i-find-all-the-elements-in-javascript-array-that-start-with-certain-lett

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!