-2

I have this simple code:

let arr = [
  'bill-items',
  'bills',
  'customer-return-items',
  'customer-returns'
]

let re = new RegExp('^b*')

arr.forEach((e) => {
  console.log(`Matching ${e}: ` + re.test(e))
})

I expect two matches and two non-matches. Strangely I get four matches! Check here: https://jsfiddle.net/kargirwar/gu7Lshnt/9/

What is happening?

Hao Wu
  • 17,573
  • 6
  • 28
  • 60
kargirwar
  • 536
  • 2
  • 7
  • 19

2 Answers2

0

Try removing the "*" as following code snippets

"*" matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)

let arr = [
  'bill-items',
  'bills',
  'customer-return-items',
  'customer-returns',
  'when-b-is-not-the-first-character',
  'b',
  '' //empty string
]

let re = new RegExp('^b')

arr.forEach((e) => {
  console.log(`Matching ${e}: ` + re.test(e))
})

The above code will match any strings that starts with letter b

Someone Special
  • 12,479
  • 7
  • 45
  • 76
0

It's quite simple

  • ^. matches the beginning of the string. Each of the four strings has a beginning

  • b* matches any number of b also zero

And so, the regex matches the biggest part of the string it can. This is ^b for the first two strings and just ^ for the others.

If you want to match only strings that begin with at least one b use /^b+/ as the + requires at least one occurrence.

BTW you can use for instance https://regex101.com/ to test your regex and visualize the matches.

derpirscher
  • 14,418
  • 3
  • 18
  • 35