Home > Web Front-end > JS Tutorial > 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
Release: 2024-10-28 05:16:30
Original
515 people have browsed it

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>
Copy after login

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)
)
Copy after login

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!

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