javascript - 确定字符串是否至少有 2 个来自数组的相同元素

标签 javascript node.js regex function

我想确定字符串是否至少有 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#someString#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/

相关文章:

regex - 我如何制作一个正则表达式来匹配出现在一行开头的 "<br>"、 "<br/>"和 "<p>"的任意组合?

javascript - 如何仅使用 JavaScript 关闭单击 anchor 时的侧边栏?

javascript - 你能调用一个在调用者上下文中返回的函数吗?

node.js - Node js 减去时间戳

ruby-on-rails - 字符串格式检查(部分随机字符串)

python - 如何获取单引号内的字符串但忽略 "' s "and " 't "?

javascript - 从 javascript 捕获 window.open

javascript - 将 tinymce 编辑器添加到元素对象而不是选择器

node.js - 按 2 个字段搜索 mongoDB

node.js - mongodb中时间戳按降序排序