JavaScript中无需遍历字符数组查找字符串匹配字符索引的方法
JS实现查找目标字符串中指定字符集首次出现的索引
要实现你描述的效果,无需手动遍历字符数组,基于正则的search方法就能快速实现,同时兼容你要求的调用形式:
方案1:封装独立工具函数(推荐,无原型污染)
实现代码:
function indexOfAny(targetStr, matchChars) { // 转义正则特殊字符,避免特殊符号匹配异常 const escapedChars = matchChars.map(char => char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) return targetStr.search(new RegExp(`[${escapedChars.join('')}]`)) }
调用示例:
indexOfAny("3.14", [".", ","]) // 返回 1 indexOfAny("3,14", [".", ","]) // 返回 1
如果没有匹配到任何字符,方法会返回-1,和原生indexOf行为一致。
方案2:扩展String原型,匹配你给出的调用形式
如果你需要直接使用"3.14".indexOf([".",","])的写法,可以扩展String原型,同时兼容原生indexOf的所有功能:
// 先保留原生indexOf方法 const rawIndexOf = String.prototype.indexOf String.prototype.indexOf = function(searchValue, fromIndex) { // 数组参数走自定义匹配逻辑 if (Array.isArray(searchValue)) { const escapedChars = searchValue.map(char => char.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) const matchReg = fromIndex === undefined ? new RegExp(`[${escapedChars.join('')}]`) : new RegExp(`(?<=.{${fromIndex}})[${escapedChars.join('')}]`) const matchIndex = this.search(matchReg) return matchIndex === -1 ? -1 : matchIndex } // 非数组参数调用原生逻辑 return rawIndexOf.call(this, searchValue, fromIndex) }
测试效果完全符合你的预期:
"3.14".indexOf([".",","]) // 1 "3,14".indexOf([".",","]) // 1
内容的提问来源于stack exchange,提问作者miorey
相关产品推荐
相关产品推荐

