![](/img/trans.png)
[英]how can I return all the elements of an array with the first letter as a capital letter
[英]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.