Reputation: 44135
I want to split a string based on the delimiters " "
and ","
(including quotation marks). How would I be able to do this? I tried doing this:
var str = '"String","String2" "String3"';
str = str.split('" "', '","');
console.log(str);
But it didn't work. I was expecting this console output:
["String", "String2", "String3"]
But I got:
[]
How do I split a string based on two delimiters? Is it possible?
Upvotes: 2
Views: 111
Reputation: 1339
You can use regex: str = str.split(/,| /)
console.log("a,b c".split(/,| /));
Upvotes: 0
Reputation: 789
let str = '"String","String2" "String3"';
str = str.split(/ |,/);
console.log(str);
let str2 = '"String","String2" "String3"';
str2 = str2.split(/" "|","|"|\n/).filter(Boolean);
console.log(str2);
let str3 = '"String","String2" "String3"';
str3 = str3.match(/[\w\d]+/g);
console.log(str3);
Upvotes: 6
Reputation: 2490
try below solution
var str = '"String","String2" "String3"';
str = str.match(/\w+|"[^"]+"/g)
str = str.map(function(x){return x.replace(/"/g, '');});
console.log('Final str : ', str);
Upvotes: 0
Reputation: 1009
You can specify regex or array as delimiter https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
Upvotes: 0