Can anyone help me to turn this string into an array of numbers without losing zeros(0)? And not using regExp
"00ghj67 h4 h000ytff700jhjk80" -> [0,0,67,4,0,0,0,700,80]
function extractNumbers(string) {
let arrNumbs = [];
let numbers = "";
for (let i = 0; i < string.length; i++) {
let elem = string.charAt(i);
if (!isNaN(elem)) {
numbers += elem;
} else if (numbers !== "") {
arrNumbs.push(parseInt(numbers));
numbers = "";
}
}
if (numbers !== "") {
arrNumbs.push(parseInt(numbers));
return arrNumbs;
}
return arrNumbs;
}
extractNumbers("00ghj67 h4 h000ytff700jhjk80");
console.log(extractNumbers(string)); //->[ 0, 67, 4, 0, 700, 80 ]
5
Answers
You can add a special case for 0.
The problem is that
parseInt(numbers)
will skip the leading zeros. So you have to handle it in a special case. I have modified your code.Turn the input string into an array of individual characters using the spread operator. Then, in the accumulator array of
reduce
, start a new string whenever we reach a digit directly after a non-digit (and also when a string containing only zero is followed by another zero). Then, for numeric characters, append it to the most recent string in the accumulator array. Finally, use the+
operator to coerce the the array of strings into an array of numbers.But if anyone is looking for regexp instead:
a shorter one: