遇到数字时将字符串拆分为两部分的数组

Split string into array of exactly two parts when a number is encountered

有没有办法在遇到数字时(最好使用split())将字符串拆分为正好由两部分组成的数组?

示例:

您可以使用 / (?=\d+)/ 拆分 space 后跟一系列数字字符:

console.log(["Nutritional Value per 100 gram", "Protein (g) 4.27"]
  .map(s => s.split(/ (?=\d+)/)));

如果您想概括这一点而不依赖于数字序列前 space 的存在,请尝试:

console.log(["Nutritional Value per100 gram", "Protein (g)4.27", "0a11b 2.2cc3"]
  .map(s => [...s.matchAll(/^\D+|(?:\d[\d.]*\D*)/g)]));

您可以使用 reg exce 获取第一个数字的索引。然后就可以拆分了。

const split = (str) => {
  const m = /\d/.exec(str);
  if (m) {
    const index = m.index;
    return [str.slice(0, index - 1), str.slice(index)];
  }
  return [str];
};
console.log(split("Nutritional Value per 100 gram"));
console.log(split("Protein (g) 4.27"));
// output: [ 'Nutritional Value per', '100 gram' ]
// output: [ 'Protein (g)', '4.27' ]

const splitFunt = (text) => {
    const arrValues = text.match(/([^\s]+)/g);
    let firstPart = '';
    let lastPart = '';
    for (let i in arrValues) {
      if (i <= arrValues.length / 2) {
       firstPart += arrValues[i] + ' ';
      } else {
       lastPart += arrValues[i] + ' ';
      }
    }
    return [firstPart, lastPart];
}

console.log(splitFunt('Nutritional Value per 100 gram'));
console.log(splitFunt('Protein (g) 4.27'));