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.

Share Improve this question asked Dec 24, 2012 at 18:49 ATOzTOAATOzTOA 36k23 gold badges99 silver badges119 bronze badges 9
  • 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
 |  Show 4 more ments

3 Answers 3

Reset to default 5
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)

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