Reputation: 13
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"]
Upvotes: 1
Views: 103
Reputation: 56895
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)]));
Upvotes: 1
Reputation: 8125
You can get index of first num using reg exce. Then can split.
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' ]
Upvotes: 0
Reputation: 726
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'));
Upvotes: 0