Ple*_*klo 8 javascript regex function node.js
我想确定字符串是否从数组中至少有2个相同的元素
const array = ["!", "?"];
const string1 = "!hello"; // should return false
const string2 = "!hello?"; // should return false
const string3 = "!hello!"; // should return true
const string4 = "hello ??"; // should return true
const string5 = "hello ?test? foo"; // should return true
const string6 = "hello ?test ?? foo"; // should return true
Run Code Online (Sandbox Code Playgroud)
我不确定会更好的是:正则表达式还是函数?任何都可以。
我尝试了这个:
const array = ["!", "?"];
const string = "test!";
array.every(ar => !string.includes(ar));
Run Code Online (Sandbox Code Playgroud)
但是它仅检测数组中是否存在至少1个元素,而不是2个。
您可以使用Array#some和String#split这样做:
const check=(array,string)=>array.some(char=>(string.split(char).length-1)>=2)
const array = ["!", "?"];
console.log(check(array,"!hello"))
console.log(check(array,"!hello?"))
console.log(check(array,"!hello!"))
console.log(check(array,"hello ??"))
console.log(check(array,"hello ?test? foo"))
console.log(check(array, "hello ?test ?? foo"))Run Code Online (Sandbox Code Playgroud)
它是如何工作的?
让我们分手吧split()!
const check=(array,string)=>
array.some(char=>
(
string.split(char)
.length-1
)>=2
)
Run Code Online (Sandbox Code Playgroud)
Array#some,测试至少一个数组元素应该通过(即?或!)char,然后算出我们有多少部分
n零件,则意味着我们有匹配的n-1地方char。(例如,2个|分割字符串转换成3个部分:a|b|c)