admin管理员组文章数量:1415119
I have an array
var months = ["January", "February", "March", "April", \
"May", "June", "July", "August", "September", "October", \
"November", "December"];
I have strings like "Nov", "October", "Jun", "June", "Sept", "Sep" etc. The point is, the string can be a substring of one of the months.
What is the best way to pare the string to be a substring of the array elements? How do I find out the index of the month?
I am looking at javascript/jQuery.
I know I can just loop through the array checking against each element using search
and break when found. I want something better.
I have an array
var months = ["January", "February", "March", "April", \
"May", "June", "July", "August", "September", "October", \
"November", "December"];
I have strings like "Nov", "October", "Jun", "June", "Sept", "Sep" etc. The point is, the string can be a substring of one of the months.
What is the best way to pare the string to be a substring of the array elements? How do I find out the index of the month?
I am looking at javascript/jQuery.
I know I can just loop through the array checking against each element using search
and break when found. I want something better.
- It's not too difficult to do manually. What have you tried? – John Dvorak Commented Dec 24, 2012 at 18:51
-
You can use
Array#forEach
but ultimately you'll need to loop through the array. – John Dvorak Commented Dec 24, 2012 at 18:53 - I need the index also, so Array#some won't work. – ATOzTOA Commented Dec 24, 2012 at 18:55
- @JanDvorak Array#forEach returns a modified array. – ATOzTOA Commented Dec 24, 2012 at 18:56
- 2 What's wrong with iterating over each item in the array and making the parison? What do you mean by "better"? Shorter code? More efficient? – Andrew Whitaker Commented Dec 24, 2012 at 18:56
3 Answers
Reset to default 5var month_index = function(target) {
target = target.toLocaleLowerCase();
return jQuery.inArray(true, jQuery.map(months, function(s) {
return s.toLocaleLowerCase().indexOf(target) > -1;
}))
};
var index_of_october = month_index("oct");
var substr = 'nov', months = ["december", "november", "feb"];
var index = months.indexOf( months.filter(function(v){ return v.indexOf(substr) >= 0;})[0]);
alert(index)
http://jsfiddle/KeMe9/
Put your array items in lower case
var txt = "Sep";
var found = false;
txt = txt.toLowerCase();
for (var i = 0; i < 12; i++) {
if (months[i].indexOf(txt) > -1) {
found = true;
break;
}
}
本文标签: javascriptHow to check if a string is a substring of any element in an arrayStack Overflow
版权声明:本文标题:javascript - How to check if a string is a substring of any element in an array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745212106a2647949.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论