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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-10-28 05:16:30418browse

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

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

Here's a breakdown of the regular expression:

(
    &quot;.*?&quot;       # double quotes + anything but double quotes + double quotes
    |           # OR
    [^&quot;,\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!

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