-1

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

David Kiss
  • 83
  • 8

1 Answers1

1

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

gog
  • 10,367
  • 2
  • 24
  • 38
  • This is no longer case insensitive. – Wiktor Stribiżew Sep 15 '22 at 14:55
  • @gog It seems to work for me, 2 question though: why >= 0 needed and why replaceAll instead of replace? it work as you wrote I just want to know why you wrote the way you did, what it does in the background? Thanks – David Kiss Sep 15 '22 at 15:00
  • 1
    `>=0` is needed because `search` returns an zero-based index or -1 if a regex did not match. You could use `match` without a comparison instead: `.filter(x => x.match(regex))`. – gog Sep 15 '22 at 15:10
  • `replaceAll` was a mistake, corrected now – gog Sep 15 '22 at 15:10