Wassim Tahraoui
Wassim Tahraoui

Reputation: 179

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. 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']

Upvotes: 2

Views: 126

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386570

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);

Upvotes: 4

Related Questions