0

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.

3
  • blog.stevenlevithan.com/archives/cross-browser-split Commented Jan 31, 2012 at 18:50
  • Why do you want to split it? Is it valid JSON? Or valid JavaScript that could be eval'd? Commented Jan 31, 2012 at 18:51
  • Its not valid JSON, using this as meta data for some reason. Commented Jan 31, 2012 at 19:33

3 Answers 3

1

I would do it this way:

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

I think it will give ["{key1:value1", "key2:value2}"], which isn't wanted.
@Borodin No, note .replace(/^{|}$/g, '') part which removes these braces from the beggining and from the end. PS. I wouldn't post it without testing.
Yes you are right. I am using this for now. But just curious why we cannot make this in single expression.
0

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

1 Comment

Consider if we have space between the braces.
0

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.

4 Comments

You should also remove first { and last } because they produse fake array values: ["", "key1:value1", "key2:value2", ""]
You are right. But there is no difference between both an expression. Any how both expression is failing in IE7. That's gives suprise to me.
Never trust Internet Explorer. It has a poor reputation for adhering to standards.
I have written this the way I would choose to for myself - without using split - and added it to my answer. This solution avoids superfluous blank array entries as well as coping with embedded whitespace in the target string if necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.