在数字之间解析时 JS 中的无限循环

Infinite loop in JS when parsing between digits

我正在尝试将一个列表拆分为有数字或无数字的子列表,而不会像 split() 那样丢失任何数据。这非常令人尴尬,但我 运行 陷入了无限循环,而且我一辈子都无法找出错误。感谢您的帮助!

const parseArg = arg => {
  const parsedList = [];
  let pos, str;
  let grabbingDigits = false;
  while (arg.length != 0) {
    pos = grabbingDigits ? arg.search(/\d/) : pos = arg.search(/^\d/);
    str = arg.substring(0,pos);
    arg = pos != -1 ? arg.substring(pos) : arg;
    parsedList.push(str);
    grabbingDigits = !grabbingDigits;
  }
  return parsedList;
}
console.log(parseArg('abc123def')); //=> should be ['abc','123','def']

只使用一个全局正则表达式可能会更容易:用 \d+ 匹配数字,用 \D+ 匹配非数字:

const parseArg = arg => arg.match(/\d+|\D+/g);
console.log(parseArg('abc123def')); //=> should be ['abc','123','def']

对于像您的原始代码这样的更具编程性的方法,在循环内,从 arg 的(当前)开始确定数字或非数字的字符数,然后 .slice适当地:

const parseArg = arg => {
  const parsedList = [];
  while (arg.length != 0) {
    const thisLength = arg.match(/^\d/)
      ? arg.match(/^\d+/)[0].length
      : arg.match(/^\D+/)[0].length;
    parsedList.push(arg.slice(0, thisLength));
    arg = arg.slice(thisLength);
  }
  return parsedList;
}
console.log(parseArg('abc123def')); //=> should be ['abc','123','def']