-2

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?

3 Answers3

2

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)
Jon
  • 428,835
  • 81
  • 738
  • 806
0

You can remove all {s and explode the string per }. Something like this:

var str = "{1} {2} {4} {abc} {abs}";
var result = str.replace(/{|}$/g,"").split(/} ?/);
document.write(result);
Shafizadeh
  • 9,960
  • 12
  • 52
  • 89
0

Try RegExp /([a-z]+|\d+)(?=\})/ig to match a-z case insensitive or digit characters followed by }

"{1} {2} {4} {abc} {abs}".match(/([a-z]+|\d+)(?=\})/ig)

console.log("{1} {2} {4} {abc} {abs}".match(/([a-z]+|\d+)(?=\})/ig))
guest271314
  • 1
  • 15
  • 104
  • 177
  • 1
    I think your pattern could be simply this `/(\w+)(?=})/g`. You don't need to escape `{` character, Also what OP mentioned in his question is just an example. I guess there maybe are some values like these: `1a`, `ba3`. – Shafizadeh Apr 17 '16 at 19:20