Extract Number From String Javascript
Does anyone know a way to extract numbers from a string in JavaScript? Example: 1 banana + 1 pineapple + 3 oranges My intent is to have the result in an array or JSON or something
Solution 1:
var result= "1 banana + 1 pineapple + 3 oranges";
result.match(/[0-9]+/g)
Solution 2:
Using String.prototype.match()
and parseInt()
:
const s = "1 banana + 1 pineapple + 3 oranges";
const result = (s.match(/\d+/g) || []).map(n =>parseInt(n));
console.log(result);
Post a Comment for "Extract Number From String Javascript"