简体   繁体   中英

Convert a string to array of number and alphabets

var string;
var splitstring = string.split("????");

my string is 12BLG123 i need the array splitstring to have elements 12,BLG,123 (The alphabets and numbers randomly vary)

 const string = `12BLG123` const splitString = string.split(/(\\d+)/).filter(i => i) console.log(splitString) 

The regex splits the string by numeric strings. Since split doesn't include the value that it is being split by, we use the capturing syntax to include the numeric strings. Empty strings are introduced if the string starts or ends with numeric strings so we use filter(i => i) to remove the empty strings (it works because empty strings are falsey values in javascript).

Though not regex or split, but you can do something like this,

 var str = "12BLG123"; var result = [].reduce.call(str, (acc, a) => { if (!acc.length) return [a]; // initial case let last = acc[acc.length - 1]; // same type (digit or char) if (isNaN(parseInt(a, 10)) == isNaN(parseInt(last.charAt(0), 10))) acc[acc.length - 1] = last + a; // different type else acc.push(a); // return the accumulative return acc; }, [] /* the seed */); console.log(result); 

这个正则表达式可能会起作用。

var splitString = string.split("[^A-Z0-9]+|(?<=[AZ])(?=[0-9])|(?<=[0-9])(?=[AZ])");

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