admin管理员组文章数量:1292995
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);
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);
Share
Improve this question
asked May 13, 2015 at 9:36
user2678132user2678132
1151 silver badge4 bronze badges
1
-
Try this in jQuery:
var $beginswitha = $(":input[name^='a']")
. Then place that variable in your indexOf statement. – Callum. Commented May 13, 2015 at 9:41
3 Answers
Reset to default 4Three things:
- You want to split by
', '
, not','
indexOf
doesn't take a regex, but a string, so your code searches for a literal^
. Usesearch
if you want to use regular expressions.indexOf
(andsearch
) do return the index where they find the sought-after term. You'll have to pare that to your expectation:== 0
. Alternatively, you can use the regextest
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);
}));
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);
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);
版权声明:本文标题:jquery - How can I find all the elements in javaScript array that start with certain letter - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741564804a2385661.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论