iamjustcoder
iamjustcoder

Reputation: 4852

Split string as key:value pair in javascript

I have a String:

"{key1:value1}{key2:value2}".

I want to split these string using regular expression as:

"key1:value1","key2:value2" .

Finally i got expression like val.split(/{(.*?)}/);

Surprisingly, this expression is not working in IE7. Just curious to know why the browser compatibility for Regular expression. And, do we have any alternate regular expression for fixing in IE7.

Upvotes: 0

Views: 2098

Answers (3)

Borodin
Borodin

Reputation: 126742

Rather than capturing the items that you want to retain (which will result in null strings between those values in the return from split) why not just split on all braces?

val.split(/[{}]+/);

Rather than trying to get split working, I would write this using a simple global match

val.match(/([^{}]+)/g);

which is fine unless there could be whitespace in the string, in which case the messier

val.match(/([^\s{}](?:[^{}]*[^\s{}])?)/g);

is necessary.

Upvotes: 0

dfsq
dfsq

Reputation: 193291

I would do it this way:

"{key1:value1}{key2:value2}".replace(/^{|}$/g, '').split('}{')

And it gives you ["key1:value1", "key2:value2"] array.

Upvotes: 1

Sid
Sid

Reputation: 7631

Are you expecting curly braces in your keys or values? If not, why not just split by '}'?

Upvotes: 0

Related Questions