0

I need to write regexp that could find a string that validates as a function argument and asterisk. I write that 'some*'.match(/^[a-z0-9]+|(\*$)/i)

But it not found asterisk. second result item is just undefined..

I plan to get string "some" and "*", also if you search in some word without asterisk at the end it must to find only that word.

Yury Shapkarin
  • 489
  • 1
  • 5
  • 13

1 Answers1

1

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);
Danziger
  • 19,628
  • 4
  • 53
  • 83