2

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. I want to split that received string to 1h and 30m to manipulate them using the 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. 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']
  • 2
    Does this answer your question? [Javascript and regex: split string and keep the separator](https://stackoverflow.com/questions/12001953/javascript-and-regex-split-string-and-keep-the-separator) – VLAZ May 26 '20 at 20:16
  • could you give us some rules, for example could there be 2 digits number like `20h` or even more 3? is it possible to have like `0h30min`? is it possible to have `1min` or do we need always a zero like this `01min`? – bill.gates May 26 '20 at 20:18
  • @VLAZ educational and all, but isn't really the problem Wassim is having – user120242 May 26 '20 at 20:24

1 Answers1

4

You could match the parts by looking for digits followed by h or m.

let str = '1h30m',
    duration = str.match(/\d+[hm]/gi);
    
console.log(duration);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392