簡體   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