You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript如何判断字符串包含指定词组/数字序列外的内容

JavaScript 字符串内容检测实现

检测逻辑满足以下任一条件即返回true:

  • 字符串包含字母内容,指定短语ANOTHER CMD不计入判定
  • 字符串包含传入的允许数字序列数组之外的数字组合,允许列表支持自定义传入任意值,默认示例值为["8809 8805", "8806 8807"]

实现代码

function checkStringContent(targetStr, allowedNumSeqs = ["8809 8805", "8806 8807"], excludePhrase = "ANOTHER CMD") {
  // 先移除指定排除的短语,避免干扰字母检测
  const processedStr = targetStr.replaceAll(excludePhrase, '');
  // 规则1校验:检测是否存在英文字母
  if (/[a-zA-Z]/.test(processedStr)) {
    return true;
  }
  // 提取字符串中所有带空格分隔的数字序列
  const numSeqsInStr = targetStr.match(/\d+(?:\s+\d+)*/g) || [];
  // 规则2校验:存在不在允许列表内的数字序列即返回true
  return numSeqsInStr.some(seq => !allowedNumSeqs.includes(seq.trim()));
}

调用示例

// 默认配置下的测试
checkStringContent("ANOTHER CMD") // false 属于排除的字母短语,无违规
checkStringContent("open folder") // true 包含排除短语外的字母
checkStringContent("8809 8805") // false 数字序列在允许列表内
checkStringContent("1234 5678") // true 数字序列不在允许列表内
checkStringContent("ANOTHER CMD 8806 8807") // false 短语合规,数字在允许列表

// 自定义允许数字序列
checkStringContent("0000 9999", ["0000 9999", "1111 2222"]) // false
checkStringContent("3333 4444", ["0000 9999", "1111 2222"]) // true

内容的提问来源于stack exchange,提问作者Arya Anish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 01:57:22