Split a String by Commas, Ignoring Commas within Double Quotes Using JavaScript
To address the challenge of splitting a string by commas while preserving double-quoted segments, we can utilize regular expressions in JavaScript. Here's how:
var str = 'a, b, c, "d, e, f", g, h';
var arr = str.match(/(".*?"|[^",\s] )(?=\s*,|\s*$)/g);
// Handle the case of no matches to prevent errors
arr = arr || [];
// Iterate over the matches and display them
for (var i = 0; i This regular expression employs two capturing groups to match substrings of interest:
- Group 1: Matches double-quoted segments ("d, e, f") using a greedy operator (.*?) to capture everything within double quotes.
- Group 2: Matches any other character sequence (e.g., "a", "g") that does not contain double quotes, commas, or whitespace characters ([^",\s] ).
The lookahead assertion (?=\s*,|\s*$) ensures that the match is followed by either a whitespace and comma or the end of the string. This ensures that we only capture comma-separated segments.
By matching both quoted and unquoted segments, this solution accurately splits the given string into an array of six elements: ["a", "b", "c", "d, e, f", "g", "h"].
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3