-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
  • 12,323
  • 4
  • 12
  • 39
kargirwar
  • 352
  • 1
  • 3
  • 15

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
  • 6,546
  • 5
  • 25
  • 50
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
  • 6,458
  • 3
  • 9
  • 25