javascript regex globally case insensitive issue

Viewed 27

I can't seem to find the solution for a regex issue I am facing:

I have an array of ticket numbers(strings) I want to filter them with regex then obviously remove the the regex string from the numbers so I end up with the numbers only. At the moment it seems that the regex str is mainly a prefix but I don't want to limit my code for something like this: /(^ex)/i It worked but if somewhy this rule breaks and it becomes a suffix maybe then my regex isn't valid then..

I want to check globally and case insensitively if the string has ex in anyway in the string(prefix, suffix, ex, EX, eX, Ex)...

const TicketNumbers = ['ex12', 'EX34', 'eX21', 'Ex77', '85ex', '767EX', '523eX', '236Ex']

const exPrefix = /ex/gi;

const exTickets = TicketNumbers
  .filter(ticket => exPrefix.test(ticket))
  .map(ticket => ticket.replace(exPrefix, ''));

Problem:

  • /ex/gi : this is ok for ex, EX for prefix and suffix but doesn't solve eX or Ex..

  • /(^ex)/i : this remove ex in all version but it is only a prefix

1 Answers

Just use String.search or String.match instead of test:

const TicketNumbers = ['ex1', '2eX', '3Ex4', '5EX6', 'foo']

const exPrefix = /ex/ig;

const exTickets = TicketNumbers
    .filter(ticket => ticket.search(exPrefix) >= 0)
    .map(t => t.replace(exPrefix, ''))

console.log(exTickets)

test and friends are broken and it's better to stay away from them

Related