7

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]
1
  • 1
    Strings usually have quotes, so it's good to add them so there's no ambiguity about where the bytes are. Voting to close due to no attempt. Commented Jul 19, 2022 at 21:30

3 Answers 3

18
var result= "1 banana + 1 pineapple + 3 oranges";
result.match(/[0-9]+/g)
Sign up to request clarification or add additional context in comments.

Comments

11

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

3 Comments

This solution breaks if the string does not contain a number. The answer by @Amrutha is safest and does not strictly assume that the string has to contain a number.
@raychz Updated my answer to address cases where the string doesn't contain numbers. The solution by Amrutha that you're recommending doesn't extract numbers at all, it extracts numerical strings.
In ES6 you can use s.match(/\d+/g)?.map(Number). Slight difference from the answer here: you get undefined rather than [] when there are no matches.
7

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

2 Comments

this and the answer from Robby are correct. So, marking any of this as answer will help future visitors.
This solution breaks if the string does not contain a number. The answer by @Amrutha is safest and does not strictly assume that the string has to contain a number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.