Splitting Strings by Commas While Ignoring Text Within Double Quotes
The task of splitting a string by commas presents a unique challenge when commas appear within double quotes. Here's how to achieve this in Javascript:
<code class="js">var str = 'a, b, c, "d, e, f", g, h'; var arr = str.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);</code>
This regex-based approach follows a specific pattern to extract substrings:
The result is an array of six elements:
arr = [ 'a', 'b', 'c', '"d, e, f"', 'g', 'h' ]
The above is the detailed content of How to Split a String by Commas While Ignoring Text Within Double Quotes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!