1

How can I split the following string?

var str = "test":"abc","test1":"hello,hi","test2":"hello,hi,there";

If I use str.split(",") then I won't be able to get strings which contain commas.

Whats the best way to split the above string?

Kobi
139k41 gold badges259 silver badges302 bronze badges
asked Feb 24, 2011 at 8:28
2
  • 3
    Are you sure that's the string that you have? What you posted is not a valid JavaScript. (Looks like a JSON without curly braces, though.) Commented Feb 24, 2011 at 8:31
  • So you notice that the colons : are not inside the string? Where do you get the string from? Commented Feb 24, 2011 at 8:33

5 Answers 5

3

I assume it's actually:

var str = '"test":"abc","test1":"hello,hi","test2":"hello,hi,there"';

because otherwise it wouldn't even be valid JavaScript.

If I had a string like this I would parse it as an incomplete JSON which it seems to be:

var obj = JSON.parse('{'+str+'}');

and then use is as a plain object:

alert(obj.test1); // says: hello,hi

See DEMO

Update 1: Looking at other answers I wonder whether it's only me who sees it as invalid JavaScript?

Update 2: Also, is it only me who sees it as a JSON without curly braces?

answered Feb 24, 2011 at 8:34
Sign up to request clarification or add additional context in comments.

Comments

0

Though not clear with your input. Here is what I can suggest.

str.split('","'); and then append the double quotes to each string

answered Feb 24, 2011 at 8:32

Comments

0

str.split('","'); Difficult to say given the formatting

if Zed is right though you can do this (assuming the opening and closing {)

str = eval(str);
var test = str.test; // Returns abc
var test1 = str.test1; // returns hello,hi
//etc
answered Feb 24, 2011 at 8:32

Comments

0

That's a general problem in all languages: if the items you need contain the delimiter, it gets complicated.

The simplest way would be to make sure the delimiter is unique. If you can't do that, you will probably have to iterate over the quoted Strings manually, something like this:

var arr = [];
var result = text.match(/"([^"]*"/g);
for (i in result) {
 arr.push(i);
}
answered Feb 24, 2011 at 8:33

Comments

0

Iterate once over the string and replace commas(,) following a (") and followed by a (") with a (%) or something not likely to find in your little strings. Then split by (%) or whatever you chose.

answered Feb 24, 2011 at 8:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.