user348173 user348173 - 2 months ago 11
Javascript Question

Regexp parse string

I have string that can look like:

2d
1m
5h


I want to parse it and get array:

[2, 'd']
[1, 'm']
[5, 'h']


I wrote the regexp:

var r = /^(\d)([mhd])$/;
var res = r.exec("2m");
console.log(res);


It outputs:
["2m", "2", "m"]


As you can see first item is excess.
How to write it properly?

Answer

You already are doing it properly. Just need to pick the right part with slice().

var r = /^(\d)([mhd])$/;
var res = r.exec("2m").slice(1, 3);
console.log(res);
Comments