简体   繁体   English

如何检查字符串是否是数组中任何元素的子字符串

[英]How to check if a string is a substring of any element in an array

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. 我有“Nov”,“October”,“Jun”,“June”,“Sept”,“Sep”等字符串。重点是,字符串可以是其中一个月的子字符串。

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. 我在看javascript / jQuery。

I know I can just loop through the array checking against each element using search and break when found. 我知道我可以通过search找到每个元素的数组检查,并在找到时中断。 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)

http://jsfiddle.net/KeMe9/ http://jsfiddle.net/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;
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何通过数组检查字符串是否具有匹配的子字符串 - How to check if string has a matching substring by array 检查字符串是否包含 JavaScript 中数组的任何元素 - Check if a string contains any element of an array in JavaScript 如何检查字符串是否以数字开头并且在javascript中不包含任何substring? - How to check if string starts with number and does not contain any substring with it in javascript? 检查数组值是否是字符串的 substring - Check if array values is a substring of a string 如何检查字符串是否包含JavaScript中的字符串数组中的子字符串 - how to check if a string contains a substring from an array of strings in JavaScript 如何检查字符串是否包含数组中的子字符串并将其拆分 - How to check if a string contains a substring from an array and split it 使用lodash检查数组元素是否包含另一个数组元素的子字符串 - Check if array element contain substring of a another array element using lodash 检查字符串中的数组元素 - Check for an array element in a string 如何检查字符串中是否存在数组元素 - How to check if an element of an array is present in a string 如何检查字符串是否包含来自 NodeJS 中子字符串数组的文本,然后在数组中找到该 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ 的索引? - How to check if a string contains text from an array of substrings in NodeJS and then find the index of that substring in the array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM