假设我有如下字符串:
"22N"
"3X"
"-12X"
"12T"
"123123T"
现在,我想拆分数字
和字母
以形成一个数组对:
[22, "N"]
[3, "X"]
[-12, "X"]
[12, "T"]
[123123, "T"]
我尝试过的:
var first = parseInt(input.substring(0, input.length - 1));
var last = input.slice(-1);
这可行,但是有没有更快的方法,因为我必须处理数百万数据。
注意:字母
是单个字符并且总是最后。
最佳答案
嗯,MDN
接下来说的是 unary plus
unary plus is the fastest and preferred way of converting something into a number
如果你相信的话,你可以采取下一种方法:
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;}
也许str.charAt(str.length - 1)
比str.slice(-1)
更快。这是一个很好的性能比较,您可以查看:https://jsperf.com/charat-vs-index/5
关于javascript - 拆分字符串中的数字和字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56136299/