admin管理员组

文章数量:1387360

'{5}<blah>{0}</blah>'

i want to turn that into:

['{5}', '<blah>', '{0}', '</blah>']

i currently use: ________.split(/({.*?})/);

but this fails when curly brace is the first character as in the case:

'{0}<blah>'

which gets turned into: ['', '{0}', '<blah>'] ... a 3 element array, not a 2

what's wrong with my regex?

Thanks!

'{5}<blah>{0}</blah>'

i want to turn that into:

['{5}', '<blah>', '{0}', '</blah>']

i currently use: ________.split(/({.*?})/);

but this fails when curly brace is the first character as in the case:

'{0}<blah>'

which gets turned into: ['', '{0}', '<blah>'] ... a 3 element array, not a 2

what's wrong with my regex?

Thanks!

Share Improve this question edited Sep 10, 2009 at 16:54 Alan Moore 75.3k13 gold badges107 silver badges161 bronze badges asked Sep 10, 2009 at 13:18 rawrrrrrrrrrawrrrrrrrr 3,6977 gold badges29 silver badges33 bronze badges 1
  • Try removing the parenthesis, and making this a one-or-more match. For example, /{.+?}/. – David Andres Commented Sep 10, 2009 at 13:26
Add a ment  | 

3 Answers 3

Reset to default 5

There's nothing wrong with your regex, but there's an issue with how you're using split. Split returns an array based on a delimiter, so if the delimiter is FIRST, it gives you the stuff to the left and right of the split item.

Just check to see if the first item == '' and remove it if it is.

This should do it:

split(/((?!^)\{.*?\})/)

The negative lookahead -- (?!^) -- succeeds iff the match does not start at the beginning of the string.

What do you think of:

'{5}<blah>{0}</blah>'.split(/{([^}]+)}/g)

The value of the curly blocks are every 2 items from the item 1.

本文标签: javascriptSplitting a string with curly braces as delimetersStack Overflow