简体   繁体   English

从数组中查找所有可能的匹配字符串和子字符串

[英]Find all possible matching string and sub-strings from an array

I was trying to find a logic to select the matching string and matching substrings from an array. 我试图找到一种逻辑,以从数组中选择匹配的字符串和匹配的子字符串。 for ex: 例如:

I have a string "3-100" and an array of strings ["3", "3-1", "3-15", "3-",3-10", "3-100"]. 我有一个字符串“ 3-100”和一个字符串数组[“ 3”,“ 3-1”,“ 3-15”,“ 3-”,3-10“,” 3-100“]。

when I loop over the array, and compare the strings, I should get true on 2 cases 当我遍历数组并比较字符串时,我应该在2种情况下为真

"3" -> true,
"3-1" -> false,
"3-15" -> false,
"3-" -> false,
"3-10" -> false,
"3-100" -> true,

How can I achieve this. 我该如何实现。 I tried .includes() which will return true for all cases except "3-15". 我尝试了.includes(),对于除“ 3-15”以外的所有情况都将返回true。 Looking forward 期待

Adjo Adjo

Using Regular expression 使用正则表达式

 var arr = ["3", "3-1", "3-15", "3-", "3-10", "3-100"]; var reg = /^3(-100)?$/; var result = arr.reduce((acc, val, ind) => { acc[ind] = reg.test(val); return acc; }, []); console.log(result); 

You could split the string and look for parts with Array#includes . 您可以分割字符串并使用Array#includes查找零件。

 var string = "3-100", parts = string.split('-').map((_, i, a) => a.slice(0, i + 1).join('-')), array = ["3", "3-1", "3-15", "3-", "3-10", "3-100"], result = array.map(s => parts.includes(s)); console.log(result); 

This should work and is backward compatible: 这应该工作并且向后兼容:

 var arr = ["3", "3-1", "3-15", "3-", "3-10", "3-100"]; var SearchA = "3"; var SearchB = "100"; for( var i=0; i< arr.length; i++) { console.log( arr[i] + " = " + ValidateValue(SearchA,SearchB,arr[i])) } function ValidateValue( A, B, value ){ var subarr = value.split("-"); if( subarr[0] != A ) return false; if( subarr.length == 1 ) return true; if( subarr[1] != B ) return false; return true; } 

You can also test it here: JS Bin 您也可以在这里进行测试: JS Bin

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

相关问题 优化获取二进制字符串的所有子字符串 - Optimize getting all sub-strings of a binary string 在一个大字符串中获取定界符之间的所有子字符串 - Get ALL sub-strings between delimiters in one large string 使用过滤器删除数组中所有出现的子字符串的衬里? - One liner to remove all occurrences of sub-strings in array with filter? 将字符串拆分为以“]开头,以“ As”结尾的子字符串 - Split a string into sub-strings starting from “ ] ” ending with “As” 在给定字符串中雕刻置换后的子字符串 - Carving permuted sub-strings in a given string 计算一个字符串中有多少个子字符串是回文 - Calculate how many sub-strings of a string are palindromes 在jquery中替换字符串中多个子字符串的多次出现 - Replace multiple occurrences of multiple sub-strings in string in jquery 接收输入字符串并返回子字符串列表以及每个子字符串的出现次数 - receiving an input string and return a list of sub-strings and the number of occurrences of each sub-string JavaScript 没有创建由唯一的空白子字符串组成的字符串? - JavaScript not creating a string made up of sole white-space sub-strings? JavaScript 字符串由正则表达式拆分结果子字符串包括空切片 - JavaScript string split by Regex results sub-strings include empty slices
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM