[英]JavaScript, split string on basis number
const str = 'scsi15';
const words = str.split(/[0-15]*$/);
Code output: Array ["scsi", ""]
,代码输出:
Array ["scsi", ""]
,
However, this is the output I want: Array ["scsi", "15"]
但是,这是我想要的输出:
Array ["scsi", "15"]
You could match by non digits or digits.您可以按非数字或数字进行匹配。
const str = 'scsi15', words = str.match(/\\D+|\\d+/g); console.log(words);
One option would be to go via Regular Expression instead of String.prototype.split
:一种选择是通过正则表达式而不是
String.prototype.split
:
const str = 'scsi15'; const re = /([az]*)(\\d*)/; const words = re.exec(str); // => ['scsi15', 'scsi', '15'] console.log(words)
You can destruct regex capturing groups if the order is always the same如果顺序始终相同,您可以破坏正则表达式捕获组
const str = 'scsi15'; const re = /(\\D*)(\\d*)/; const [_, word, num] = re.exec(str); // _, is first item. Could be just , console.log(word, num)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.