Louise Godec
Louise Godec

Reputation: 249

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]

Upvotes: 7

Views: 23586

Answers (3)

Sagar V
Sagar V

Reputation: 12478

Use this regex

  • / -> start
  • \d+ -> digit
  • /g -> end and g for global match

var str = "1 banana + 1 pineapple + 3 oranges",
  mats = [];
str.match(/\d+/g).forEach(function(i, j) {
  mats[j] = parseInt(i);
});
console.log(mats);

Upvotes: 7

Robby Cornelissen
Robby Cornelissen

Reputation: 97120

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);

Upvotes: 11

Amrutha Mandadi
Amrutha Mandadi

Reputation: 196

var result= "1 banana + 1 pineapple + 3 oranges";
result.match(/[0-9]+/g)

Upvotes: 18

Related Questions