Home  >  Article  >  Web Front-end  >  How to Split a String by Commas While Ignoring Text Within Double Quotes in JavaScript?

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

DDD
DDDOriginal
2024-10-26 17:46:30827browse

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>

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' ]

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!

Statement:
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