Search code examples
javascriptregexnon-greedy

Javascript regular expressions modifier U


I have a string

"{1} {2} {4} {abc} {abs}"

and the regular expression

/\{(.+)\}/g

In PHP regular expressions i can use modifier "U" (U modifier: Ungreedy. The match becomes lazy by default). If i use /\{(.+)\}/gU my response looks like this:

Array (5) [ "1", "2", "4", "abc", "abs" ]

In javascript no modifier U. Without this modifier my response looks like this:

Array (1) [ "1 2 4 abc abs" ]

How i can do this?


Solution

  • One way is to make the + ungreedy by adding the ? modifier:

    "{1} {2} {4} {abc} {abs}".match(/\{(.+?)\}/g)
    

    Another way would be to replace . with "anything except closing brace":

    "{1} {2} {4} {abc} {abs}".match(/\{([^}]+)\}/g)