user3187960
user3187960

Reputation: 337

Array on number from string in Javascript

I am trying to get an array of numbers from a string that does not have a token to use as a split.

Example:

var myString = 'someString5oneMoreString6';

Expected result :

var result = [5, 6];

How to archive this with javascript before ES2015?

Upvotes: 0

Views: 51

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386560

You could match all digits and convert the result to numbers.

var string = 'someString5oneMoreString6',
    array = string.match(/\d+/g);

for (var i = 0; i < array.length; i++) array[i] = +array[i];

console.log(array);

Upvotes: 1

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

you can split by regex and map to process.

var str = 'someString5oneMoreString6';

const array = str.split(/[a-zA-Z]+/).filter(x => x).map(x => Number(x));

console.log(array);

Upvotes: 0

Related Questions