• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Quantifier Greediness

As we’ve already seen, JavaScript quantifiers are “greedy” by default. That means they match the most characters they can, consistent with the regular expression they’re in. For example, we tried to change the text "That is some text, isn't it?" to "That's some text, isn't it?" by replacing matches to the regular expression /.*is/ with That’s. However, /.*is/ didn’t match That is; it matched That is some text, is instead, because quantifiers are greedy. That made the result of our code "That'sn't it?", which is not what we wanted.

To fix the problem, you can make quantifiers less greedy. In fact, to match the minimum number of times possible, you follow the quantifier with a question mark (?):


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint