简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM