我想确定字符串是否至少有 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
我不确定哪个更好:正则表达式还是函数?任何一个都可以。
我试过这个:
const array = ["!", "?"];
const string = "test!";
array.every(ar => !string.includes(ar));
但它只检测数组中是否至少有 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"))
它是如何工作的?
让我们分开(我的意思是split()
)!
const check=(array,string)=>
array.some(char=>
(
string.split(char)
.length-1
)>=2
)
- 首先,使用
Array#some
,它测试数组中至少有一个元素应该通过(即?
或!
) - 按
char
分割字符串,并计算我们有多少部分- 如果我们有
n
个部分,这意味着我们有n-1
个位置与char
匹配。 (例如 2|
将字符串分成 3 部分:a|b|c
)
- 如果我们有
- 最后,测试我们是否有 2 个或更多分隔符
关于javascript - 确定字符串是否至少有 2 个来自数组的相同元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58183313/