1

I have a string that looks like this

"a,b,c,"Mozilla/5.0,(compatible;,MSIE,9.0;,Windows,NT,6.1;,Trident/5.0)",d,e"

I am trying to split this string by "," and get extract the individual values. Now, what it does is, it splits the part "Mozilla/5.0,(compatible;,MSIE,9.0;,Windows,NT,6.1;,Trident/5.0)" also and I get this as the final result

["a", "b", "c", ""Mozilla/5.0", "(compatible;", "MSIE", "9.0;", "Windows", "NT", "6.1;", "Trident/5.0)"", "d", "e"]

Is there a way to make it not split the substring? Basically I am trying to get this after split

["a", "b", "c", "Mozilla/5.0,(compatible;,MSIE,9.0;,Windows,NT,6.1;,Trident/5.0)", "d", "e"]
1

1 Answer 1

6

You can use a regular expression, and utilize negative lookahead for non-" characters followed by the ending ",, which would indicate that the current comma is inside a quoted string:

const str = `a,b,c,"Mozilla/5.0,(compatible;,MSIE,9.0;,Windows,NT,6.1;,Trident/5.0)",d,e,"foo,bar,quoted",f,g`;
console.log(str.split(/,(?![^"]+",)/))

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

Comments

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.