Jack Bashford
Jack Bashford

Reputation: 44135

Split string on two delimiters?

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

Answers (4)

Joe Belladonna
Joe Belladonna

Reputation: 1339

You can use regex: str = str.split(/,| /)

console.log("a,b c".split(/,| /));

Upvotes: 0

Piterden
Piterden

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

Shiv Kumar Baghel
Shiv Kumar Baghel

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

Nikko Khresna
Nikko Khresna

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

Related Questions