[英]Split a string and keep the splitter
I'm making a Discord Bot with Node.js and Discord.js, and I'm trying to achieve some kind of time reader, when a user sends something in this format 1h30m
, I want to manipulate some timer.我正在使用 Node.js 和 Discord.js 制作 Discord Bot,并且我正在尝试实现某种时间阅读器,当用户发送一些想要以这种格式操作的东西时
1h30m
, I want to split that received string to 1h
and 30m
to manipulate them using the str.endsWith('')
.我想将收到的字符串拆分为
1h
和30m
以使用str.endsWith('')
操作它们。
let str = '1h30m';
if (!(/[^dhms0-9]/ig).test(str)) {
console.log('RegExp Success.');
duration = str.split(/[0-9]/);
console.log(duration);
}
I made a condition that is only true when it has only numbers or any of the letter 'd', 'h', 'm' and 's' and nothing else.我做了一个条件,只有当它只有数字或任何字母“d”、“h”、“m”和“s”时才成立,没有别的。 It detects it fine but when i split by numbers i get following array:
它检测得很好,但是当我按数字拆分时,我得到以下数组:
[ '', 'h', '', 'm' ]
and what i want to get is我想得到的是
['1h', '30m']
You could match the parts by looking for digits followed by h
or m
.您可以通过查找后跟
h
或m
的数字来匹配这些部分。
let str = '1h30m', duration = str.match(/\d+[hm]/gi); console.log(duration);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.