Categories
JavaScript Answers

How to split a string by commas but ignore commas within double-quotes using JavaScript?

Spread the love

Sometimes, we want to split a string by commas but ignore commas within double-quotes using JavaScript.

In this article, we’ll look at how to split a string by commas but ignore commas within double-quotes using JavaScript.

How to split a string by commas but ignore commas within double-quotes using JavaScript?

To split a string by commas but ignore commas within double-quotes using JavaScript, we can use the match method.

For instance, we write

const str = 'a, b, c, "d, e, f", , h, "i"';
const array = str.match(/("[^"]*")|[^,]+/g);
console.log(array);

to call str.match with a regex that matches substrings with commas but ignore commas within double-quotes.

We use ("[^"]*") to ignore the double quotes.

And we use [^,] to match the commas.

The g flag makes match return all matches.

array has all the matches.

Conclusion

To split a string by commas but ignore commas within double-quotes using JavaScript, we can use the match method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *