Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 else.

Result:

[1,1,3]
like image 746
Louise Godec Avatar asked Mar 01 '17 12:03

Louise Godec


2 Answers

var result= "1 banana + 1 pineapple + 3 oranges";
result.match(/[0-9]+/g)
like image 79
Amrutha Mandadi Avatar answered Oct 21 '22 00:10

Amrutha Mandadi


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);
like image 45
Robby Cornelissen Avatar answered Oct 20 '22 23:10

Robby Cornelissen