Separate a string using commas but disregard any commas inside quotation marks

Similar Question:
JavaScript code for parsing CSV data

There is a string that looks like this:

"display, Name" <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d49584e497d49584e49135e5250">[email protected]</a>>, display" Name <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97e3f2e4e3d7e3f2e4e3b9f4f8fa">[email protected]</a>>, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d29382e291d29382e29733e3230">[email protected]</a>

The goal is to split this string into an array.

array[0] = "\"display, Name\" <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98ecfdebecd8ecfdebecb6fbf7f5">[email protected]</a>>"
array[1] = "display" Name <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9beffee8efdbeffee8efb5f8f4f6">[email protected]</a>>"
array[2] = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="116574626551657462653f727e7c">[email protected]</a>"

This is the current code being used:

var comma = inQuotes = false;
for(var i=0;i<str.length;i++) {
            if (str[i] == '"') inQuotes = !inQuotes;
            comma = (str[i] == "," && !inQuotes)  ? true : false;
            item += (!comma) ? str[i] : "";
            if(comma || i == str.length-1) {  
                items.push(item);
                item = "";
            }    
        } 

An issue arises when there is a single double quote without a closing one within a string.

Your assistance on this matter would be greatly appreciated. Thank you.

Answer №1

I gave this a try and it worked well with the provided string on jsfiddle

var text = '"display, Name" <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b3f2e383f0b3f2e383f65282426">[email protected]</a>>, display" Name <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f286978186b286978186dc919d9f">[email protected]</a>>, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="304455434470445543441e535f5d">[email protected]</a>';
var matches = text.match(/"(.*?)"(.*?),|(.*?),|(.*?)$/g); 
matches.pop();
matches // [""display, Name" <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="641001171024100117104a070b09">[email protected]</a>>,", " display" Name <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f6b7a6c6b317c7072">[email protected]</a>>,", " <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="364253454276425345421855595b">[email protected]</a>"]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Headers cannot be set again after they have been sent to the client in Express Node

I attempted to create a post request for login with the following code: router.post('/login', async(req, res) =>{ const user = await User.findOne({gmail: req.body.gmail}) !user && res.status(404).json("user not matched") c ...

Introducing a Node JS web application unaccompanied by hosting services

As I prepare for a coding competition and want to display my computer's IP address, I am wondering if it is safe to type in my home computer's IP once I start serving the webapp before leaving my house. Apologies if this question seems silly. ...

Remove HTML element and launch in a separate browser tab while preserving styles

I am currently working on developing a single-page application with Polymer3 (Javascript ES6 with imports). One of the key functionalities of my application involves moving widgets to new browser windows, allowing users to spread them across multiple scree ...

Is there a way to update a JSON file using React?

I'm looking for a solution to update a JSON file in React. Is it possible? Below is the code snippet that executes when an HTML element is clicked. Ultimately, it invokes VoteTracking, the function responsible for updating the JSON file. handleC ...

A guide on executing a double click action on an element in Selenium Webdriver with JavaScript specifically for Safari users

Having trouble double clicking an element in Safari using Java / Webdriver 2.48. All tests work fine on IE, Chrome, and Firefox but Safari does not support Actions. Currently attempting: executor.executeScript("arguments[0].dblclick();", element); or ...

Connecting to a console through telnetlib using a Python script

Greetings! I am currently a tcl user branching out into Python to broaden my skills and compare the two languages. Tcl seems to be falling out of favor, so I'm eager to expand my knowledge with Python. Today, I've tackled a task that involves au ...

Unable to get Mongoose's Required field to work in conjunction with Enum validation

Encountering issues with Mongoose Required true and Enum validation when using updateone await MonthlyTarget.updateOne({website: req.body.website, year: req.body.year, month: req.body.month}, req.body, {upsert: true}); Model 'use strict'; import ...

Verifying that utilizing a factory is the most effective method for developing a versatile click count listener

In my quest to enhance the functionality of click events, I have devised a click count factory. This factory creates a clickCountObj to keep track of the number of clicks and implements a new function for capturing click events on a specified element and r ...

Make window.print() trigger the download of a PDF file

Recently, I added a new feature to my website allowing users to download the site's content by following these instructions: Printing with Javascript || Mozilla Dev. Essentially, the user can print a newly formatted site stored in a hidden iframe. Now ...

The inclusion of a content editable feature within a carousel is leading to unexpected event propagation

I am dynamically creating an editable div using the code snippet below. <div class='reflection-field' contenteditable="true" data-number="${index}"></div> Expected Outcome: When I click on the generated div, I anticipate that the c ...

Configuring Tailwind CSS with PostCSS in a Nuxt project

Error Message "In order to avoid issues with features like alias resolving inside your CSS, please make sure to use build.postcss in your nuxt.config.js file instead of an external configuration file. Support for external config files will be depreca ...

Transforming JSON data into an interactive table with HTML

After spending four days searching for a solution, I am still unable to figure out my problem. My goal is to convert a JSON string data retrieved from a URL into a dynamic table using JQuery and JavaScript. To achieve this, I need to load the JSON string ...

Is there no body sent in the $.ajax post request?

My server is returning an error when I try to make a simple post request. It's saying that the post request has no body and all the keys have an "undefined" value. Here is the code for my post request: let alert_title = 'Alert'; let alert ...

How can I retrieve the values of jQuery select2 tag list in ASP.NET?

I am looking to retrieve the selected values from the jQuery Select2 plugin in my ASP.NET code behind. Below is a snippet of my code: Client Side: <select id="ddlcountry" runat="server" class="select" style="width: 100%;"> ...

Issue with JavaScript function not triggering in Internet Explorer

Here is the code snippet I am working with: <body onLoad="subcatSelection();"> The function that should run on body load is located in a .js file that is included using this code: <script type="text/javascript" src="bincgi/search_lists.js"& ...

React and Material-UI issue: Unable to remove component as reference from (...)

My React components are built using Material-UI: Everything is running smoothly MainView.js import React, { Component } from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import { List, ListItem } from ...

Can you tell me how to add a variable to an array of objects in JavaScript?

I am currently engaged in a small project aimed at: Reading data from a CSV file (such as employee names and shifts) Displaying this data on FullCalendar. How can I incorporate the CSV result into this line of code: { id: 'a', title: 'Audi ...

How can Typescript help enhance the readability of optional React prop types?

When working with React, it is common practice to use null to indicate that a prop is optional: function Foo({ count = null }) {} The TypeScript type for this scenario would be: function Foo({ count = null }: { count: number | null }): ReactElement {} Wh ...

Dynamic v-if condition based on data binding

Is it possible to bind a v-if directive to data? I have an array of objects that represent navigation links or buttons, such as login and logout. Each object in this array has a 'v-if' property where the condition is defined as a string. Sample ...

Rounded Corners on an HTML5 Canvas Triangle

Hi there, I'm relatively new to working with HTML5 Canvas and I'm currently attempting to create a triangle with rounded corners. So far, I've experimented with: ctx.lineJoin = "round"; ctx.lineWidth = 20; However, I haven't been suc ...