![](/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.