You need to enable JavaScript to run this app. 如何实现不区分大小写的字符串包含指定子串检测功能
优惠活动
大模型
产品
解决方案
定价
更多

如何实现不区分大小写的字符串包含指定子串检测功能

不区分大小写的字符串包含检测实现方案

实现思路

  • 将原始字符串和待匹配子串统一转换为相同大小写(全小写/全大写),再调用原生includes()方法判断,实现简单且兼容性好
  • 无需额外处理特殊字符,比正则实现方案适用性更强

基础实现代码

function caseInsensitiveIncludes(str, subStr) {
  // 兼容原生includes逻辑:空字符串始终返回true
  if (subStr === '') return true
  return str.toLowerCase().includes(subStr.toLowerCase())
}

测试用例验证

caseInsensitiveIncludes('ABCdef', 'abc') // 输出 true
caseInsensitiveIncludes('AbCdef', 'abc') // 输出 true
caseInsensitiveIncludes('abcdef', 'abc') // 输出 true
caseInsensitiveIncludes('defghi', 'abc') // 输出 false

多语言兼容优化

如果需要处理包含非英语的Unicode字符(比如德语、法语的特殊字母),可以替换为toLocaleLowerCase()适配本地语言的大小写规则:

function caseInsensitiveIncludes(str, subStr) {
  if (subStr === '') return true
  return str.toLocaleLowerCase().includes(subStr.toLocaleLowerCase())
}

注意事项

不推荐直接使用带i修饰符的正则实现,若待匹配子串包含.、*、?、+等正则特殊字符时,会出现非预期的匹配结果,需要额外做字符转义,反而增加了代码复杂度。

内容的提问来源于stack exchange,提问作者new Q Open Wid

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 22:48:02