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