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 compare 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.
var 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)
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;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.