Home > Web Front-end > JS Tutorial > body text

How to Split a String by Commas While Preserving Commas Within Double Quotes in JavaScript?

Mary-Kate Olsen
Release: 2024-10-27 01:13:30
Original
106 people have browsed it

How to Split a String by Commas While Preserving Commas Within Double Quotes in JavaScript?

Splitting Strings by Commas While Preserving Commas Within Double Quotes in JavaScript

When working with strings containing both commas and double-quoted sections, it becomes necessary to split the string into elements while keeping the double-quoted portions intact. This can be particularly challenging in JavaScript due to the inconsistency in handling double quotes.

To effectively split a string in this manner, you can utilize a regular expression that identifies and separates tokens based on specific criteria. Consider the following approach:

<code class="javascript">var str = 'a, b, c, "d, e, f", g, h';
var arr = str.match(/(&quot;.*?&quot;|[^&quot;,\s]+)(?=\s*,|\s*$)/g);</code>
Copy after login

This regular expression consists of two parts:

  • (".*?"): This part matches any double-quoted substring, where the double quotes are included.
  • (1 ): This part matches any non-empty substring that doesn't contain double quotes, commas, or spaces.

The (?=s*,|s*$) part is a positive lookahead assertion that ensures that the match is followed by a comma and whitespace or the end of the string. This prevents the splitting of double-quoted subsections.

The resulting array arr will contain six elements: ["a", "b", "c", "d, e, f", "g", "h"].

By employing this regular expression, you can accurately split a string by commas while preserving the integrity of double-quoted sections, making it suitable for many data manipulation tasks.


  1. ",s

The above is the detailed content of How to Split a String by Commas While Preserving Commas Within Double Quotes in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!