简体   繁体   中英

Split number and alphabets in string

Suppose I have strings like the ones below:

"22N"
"3X"
"-12X"
"12T"
"123123T"

Now, I want to split the numbers and alphabets to form an array of pairs:

[22, "N"]
[3, "X"]
[-12, "X"]
[12, "T"]
[123123, "T"]

What I tried:

var first = parseInt(input.substring(0, input.length - 1));
var last = input.slice(-1);

This works, but is there any faster way, because I have to process millions of data.

Note : alphabets are single character and always last .

Well, MDN says next about the unary plus

unary plus is the fastest and preferred way of converting something into a number

If you believe it, you can take next approach:

 let tests = ["22N", "3X", "-12X", "12T", "123123T"]; const splitNumLetter = (str) => [+str.slice(0, -1), str.slice(-1)]; tests.forEach(s => console.log(splitNumLetter(s))); 
 .as-console {background-color:black !important; color:lime;} .as-console-wrapper {max-height:100% !important; top:0;} 

And maybe str.charAt(str.length - 1) is faster than str.slice(-1) . Here is a good performance comparison you can check: https://jsperf.com/charat-vs-index/5

This comes to my mind,

var str="22N";
str=str.split('');
var last = str.pop(); 
var last = str.join('');

By analyzing the pattern of your strings, numbers and letters are always left or right, never in the middle of the others. So, the fastest and code-cleanest way to achieve this is by using replace with regex.

The regex is necessary only once, since following this pattern I mention you can extract the numbers first and then just replace those extracted numbers from the same string.

Lets say you have your elements in an array variable:

var elements = [
    "22N",
    "3X",
    "-12X",
    "12T",
    "123123T"
];

And then, you just need to loop trough every of them, no matter how much elements are present, you can use the forEach() function after defining your final array:

var splitElements = [];
elements.forEach((string)=>{
    let numbers = string.replace(/[a-zA-Z]/g, ''),
        letters = string.replace(numbers,'');
   splitElements.push([numbers,letters])
});

And then you can see the result at splitElements . See how it works:

 var elements = [ "22N", "3X", "-12X", "12T", "123123T" ], splitElements = []; elements.forEach((string)=>{ let numbers = string.replace(/[a-zA-Z]/g, ''), letters = string.replace(numbers,''); splitElements.push([numbers,letters]) }); console.log(splitElements); 

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