SOURCE

// 定义一个函数来查找字符串中第一个匹配项的索引
function findRunIndex(input) {
  // 去除空格并查找 "run" 的索引
  const cleanedInput = input.replace(/\s+/g, ''); // 去除空格
  const runIndex = cleanedInput.indexOf('run');

  if (runIndex !== -1) {
    // 如果找到匹配项,计算在原始字符串中的索引
    let indexInOriginal = 0;
    for (let i = 0; i < input.length; i++) {
      if (input[i] !== ' ') {
        // 只计算非空格字符的索引
        if (indexInOriginal === runIndex) {
          return i; // 返回在原始字符串中的索引
        }
        indexInOriginal++;
      }
    }
  }

  return -1; // 如果没有找到匹配项,返回 -1
}

// 测试示例
const input1 = "arun";
const input2 = "a b runrun";
const input3 = "a r u n";

const index1 = findRunIndex(input1);
const index2 = findRunIndex(input2);
const index3 = findRunIndex(input3);

console.log(index1); // 输出 3
console.log(index2); // 输出 4
console.log(index3); // 输出 6
console 命令行工具 X clear

                    
>
console