0

I need to split a string in javascript (no jquery). This is basically received fron csv. so, i have a string,

string = '"abc, xyz, mno","lmn, pqr, bcd, jkl"';

Note: Number of commas in quoted parts is not fixed for example, "abc, xyz, mno" can also be "abc, xyz, mno, klm, ..." or "lmn, pqr, bcd, jkl" could have been just "lmn"; i.e no comma at all.

I want to split it as

str1 = 'abc, xyz, mno';
str2 = 'lmn, pqr, bcd, jkl';

I can't do this with string.split(",");, due to undefined number of commas.

Thanks for any help in advance.

15
  • Why can't you use string.split('","'); and then remove the excess " with string.replace("\"", ""); ? Commented Aug 28, 2018 at 19:20
  • string.split(",") tends to split the string on all the commas. so when i string.split() on '"abc, xyz, mno","lmn, pqr, bcd, jkl"' it will return 7 parts not 2 :( Commented Aug 28, 2018 at 19:23
  • I corrected .. I meant to split on the quotes AND commas Commented Aug 28, 2018 at 19:23
  • Why not split on ," ? Commented Aug 28, 2018 at 19:23
  • 1
    Does JSON.parse("[" + '"abc, xyz, mno","lmn, pqr, bcd, jkl"' + "]") work? Commented Aug 28, 2018 at 19:25

2 Answers 2

1

You can specify multiple characters in the String#split method :

str.split('","')

Demo:

let str = '"abc, xyz, mno","lmn, pqr, bcd, jkl"';

let result = str.split('","')
console.log(result);


If you want to get rid of the quotes, juste add a

.map(s => s.replace('"',''))

Demo:

let str = '"abc, xyz, mno","lmn, pqr, bcd, jkl"';

let result = str.split('","').map(s => s.replace('"',''));
console.log(result);

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

1 Comment

Thanks for your answer @Zenoo, It does work if the string has quotes. Since quotes are optional, I cannot use this solution. However, I have found the solution on duplicate link provided. :)
0

This is probably best done with a regular expression. But, since they aren't my strongest area, here's how it could be done with a combination of String.split(), Array.map(), and String.replace():

let input = '"abc, xyz, mno","lmn, pqr, bcd, jkl"';

// Split where "," is found
// Create a new array that is a copy of the original
// but with \" removed from the elements
let output = input.split('","').map(s => s.replace('\"',''));

console.log(output);

1 Comment

Thanks for your answer @Scott, It does work if the string has quotes. Since quotes are optional, I cannot use this solution. However, I have found the solution on duplicate link provided. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.