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

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

DDD
Release: 2024-10-26 17:46:30
Original
826 people have browsed it

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

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(/(&quot;.*?&quot;|[^&quot;,\s]+)(?=\s*,|\s*$)/g);</code>
Copy after login

This regex-based approach follows a specific pattern to extract substrings:

  • ("".*?" or [^",s] ): Matches either segments enclosed in double quotes ("d, e, f") or sequences without quotes, commas, or spaces (a).
  • ((?=s*,|s*$)): Ensures matches are followed by either a comma and whitespace or the end of the string, ensuring proper splitting.

The result is an array of six elements:

arr = [ 'a', 'b', 'c', '"d, e, f"', 'g', 'h' ]
Copy after login

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!

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
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!