Question

'{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!

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top