You need an additional capturing group around the first [a-z0-9]
part and the second one should be made optional with ?
.
Also, the |
should not be there, as that's specifying two different alternatives, so your RegExp
is actually trying to match /^[a-z0-9]+/i
and, if it doesn't, then it tries /(\*$)/i
, which is not what you want. That's why you get undefined
even if the asterisk is there and also why anything that ends with an asterisk and doesn't start with a-z0-9
, like _*
, will also match.
Here's an example with all these changes:
const match1 = 'some'.match(/^([a-z0-9]+)(\*)?$/i);
const match2 = 'some*'.match(/^([a-z0-9]+)(\*)?$/i);
console.log(match1);
console.log(match2);
If you want to get rid of the first match and only get the asterisk one if it is there, you can use Array.prototype.slice()
and Array.prototype.filter()
:
const match1 = ('some'.match(/^([a-z0-9]+)(\*)?$/i) || []).slice(1).filter(Boolean);
const match2 = ('some*'.match(/^([a-z0-9]+)(\*)?$/i) || []).slice(1).filter(Boolean);
console.log(match1);
console.log(match2);