简体   繁体   中英

Javascript split by numbers using regex

I'm trying to come up with a regex that will do following. I have a string

var input_string = "E100T10P200E3000T3S10";

var output=input_string.split(**Trying to find this**);

this should give an array with all the letters in order with repetitions

output = ["E","T","P","E","T","S"]

See below. \\d+ means one or more digits; filter (x => x) removes empty strings that can appear in the beginning or the end of the array if the input string begins or ends with digits.

 var input_string = "E100T10P200E3000T3S10"; var output = input_string.split (/\\d+/).filter (x => x); console.log (output);

You can use regex replace method. First replace all the digits with empty string and then split the resultant string.

 const input_string = 'E100T10P200E3000T3S10'; const ret = input_string.replace(/\\d/g, '').split(''); console.log(ret);

We can try just matching for capital letters here:

 var input_string = "E100T10P200E3000T3S10"; var output = input_string.match(/[AZ]/g); console.log(output);

Another approach is spread the string to array and use isNaN as filter callback

 var input_string = "E100T10P200E3000T3S10"; var output = [...input_string].filter(isNaN); console.log(output);

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