Shantanu Madane
Shantanu Madane

Reputation: 615

How to get Numbers from a String

Getting Numbers from a string and inserting them into array. splitting the string would result into single character and thus does not solve my problem.

var str="(235+456+2+3-6-(2*5))"

Output Must be:
[235,456,2,3,6,2,5]

Upvotes: 1

Views: 77

Answers (3)

Yaroslav
Yaroslav

Reputation: 31

If we are talking about number output:

"(235+456+2+3-6-(2*5))".match(/\d+/g).map(e=>+e);

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92894

The solution using String.match function:

var str="(235+456+2+3-6-(2*5))"
    numbers = str.match(/\b\d+?\b/g);

console.log(numbers);  // ["235", "456", "2", "3", "6", "2", "5"]

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386868

You could use a regular expression for it. It looks only for connected numbers.

console.log('(235+456+2+3-6-(2*5))'.match(/\d+/g));

Upvotes: 2

Related Questions