Comma-separated String Find

Benchmark created on


Test runner

Ready to run.

Testing in
TestOps/sec
checkByIndexOfWithBoundary

const testStr1 = "张三.1 , 李四.2,王五.3  ,赵六.4";
console.log(checkByIndexOfWithBoundary(testStr1, "李四.2")); // true(中间项,带空格)
console.log(checkByIndexOfWithBoundary(testStr1, "王五.3")); // true(带尾随空格)
console.log(checkByIndexOfWithBoundary(testStr1, "赵六.4")); // true(结尾项)
console.log(checkByIndexOfWithBoundary(testStr1, "张三.0")); // false(无匹配)
console.log(checkByIndexOfWithBoundary(testStr1, "李四"));   // false(部分匹配)

/**
 * 高性能检查:indexOf + 边界校验(兼容空格/点号/无特殊字符)
 * @param {string} commaStr - 逗号分隔字符串(可含空格、点号)
 * @param {string} target - 目标项(可含点号)
 * @returns {boolean} 是否包含目标项(独立项)
 */
function checkByIndexOfWithBoundary(commaStr, target) {
  const targetLen = target.length;
  const strLen = commaStr.length;
  let pos = commaStr.indexOf(target);

  // 没找到目标,直接返回false
  if (pos === -1) return false;

  // 循环检查所有匹配位置(避免漏检,比如多个重复项)
  while (pos !== -1) {
    // 检查前边界:开头 / 前一个字符是逗号/空格
    const prevOk = pos === 0 || /[, ]/.test(commaStr[pos - 1]);
    // 检查后边界:结尾 / 后一个字符是逗号/空格
    const nextOk = (pos + targetLen) === strLen || /[, ]/.test(commaStr[pos + targetLen]);

    // 前后边界都符合,说明是独立项
    if (prevOk && nextOk) return true;

    // 继续找下一个匹配位置(避免重复匹配同一位置)
    pos = commaStr.indexOf(target, pos + 1);
  }

  // 所有匹配位置都不符合边界规则
  return false;
}
ready
checkByIndexOfWithSpace

const testStr1 = "张三.1 , 李四.2,王五.3  ,赵六.4";
console.log(checkByIndexOfWithSpace(testStr1, "李四.2")); // true(中间项,带空格)
console.log(checkByIndexOfWithSpace(testStr1, "王五.3")); // true(带尾随空格)
console.log(checkByIndexOfWithSpace(testStr1, "赵六.4")); // true(结尾项)
console.log(checkByIndexOfWithSpace(testStr1, "张三.0")); // false(无匹配)
console.log(checkByIndexOfWithSpace(testStr1, "李四"));   // false(部分匹配)

function checkByIndexOfWithSpace(commaStr, target) {
  // 去除所有项前后的空格
  const trimmedStr = commaStr.replace(/\s*,\s*/g, ',').replace(/^\s+|\s+$/g, '');
  const wrappedStr = `,${trimmedStr},`;
  const wrappedTarget = `,${target.trim()},`;
  return wrappedStr.indexOf(wrappedTarget) !== -1;
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.