Search code examples
javascriptstringsplittext-manipulation

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


Is there a way to split a string into an array of exactly two parts when a number is encountered (preferably using split())?

Examples:

  • "Nutritional Value per 100 gram" ==> ["Nutritional Value per", "100 gram"]
  • "Protein (g) 4.27" ==> ["Protein (g)", "4.27"]

Solution

  • You can use / (?=\d+)/ to split on a space followed by a sequence of digit characters:

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

    If you want to generalize this and not rely on the presence of a space before the digit sequence, try:

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