Split a String by Commas and Ignore Those Within Double Quotes (JavaScript)
When working with strings, it can be necessary to split them into an array of elements based on a specified delimiter. However, sometimes the delimiter occurs within double-quotes, which should be ignored while splitting.
Consider the following string that needs to be converted into an array of six elements: "a, b, c, "d, e, f", g, h". The goal is to separate each element while ignoring the commas enclosed in double quotes.
One approach is to use regular expressions:
<code class="javascript">var str = 'a, b, c, "d, e, f", g, h'; var arr = str.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);</code>
Here's a breakdown of the regular expression:
( ".*?" # double quotes + anything but double quotes + double quotes | # OR [^",\s]+ # 1 or more characters excl. double quotes, comma or spaces of any kind ) (?= # FOLLOWED BY \s*, # 0 or more empty spaces and a comma | # OR \s*$ # 0 or more empty spaces and nothing else (end of string) )
This regex will capture either double-quoted strings or any other characters that are not commas or spaces, preventing the quoted commas from being split.
The arr array will contain the split elements, which can then be logged or used for further processing.
The above is the detailed content of How to Split a String by Commas While Ignoring Commas Within Double Quotes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!