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

Switch to using addresses instead of latitude and longitude coordinates when utilizing the Google Maps API

I am looking to utilize Google Map Markers to indicate the locations where our services are offered. The code I have created using latitude and longitude is functioning properly, however, for my project I need to display city names instead of lat/long ...

What is the solution for the error "Build error occurred ReferenceError: self is not defined" when building a NextJs application?

pages/components/moru-sdk.js // https://libraries.io/npm/moru-web-sdk import { MoruCheckout } from "moru-web-sdk"; function MoruService() { const options = { access_key: "test_9425294388834bdface7d1b58fd538bf67627d9408fe4f258982 ...

Ways to fix vulnerabilities found in an NPM audit

Upon conducting an NPM audit, I found 5 critical issues. To address 4 of them, I attempted to update @storybook/addon-essentials & @storybook/react, as they were marked as "patched in >=x.x.x", indicating that the latest versions should have resolved t ...

Is there a way to modify the spacing between labels and text in the TextBox MUI component while using custom label sizes?

I've customized a material ui TextField component by increasing the font size of the label. However, I'm facing an issue where the gap in the border for the label remains unchanged despite the larger text size. I couldn't find any solution ...

Suggestions for a JavaScript tool that automatically crops images

Is there a tool available, either browser-based or in Java, that can analyze an uploaded image, identify different characters within it, and crop them out into separate images? For instance, if this image contains three unique runic symbols, I would like ...

Is there a different term I can use instead of 'any' when specifying an object type in Typescript?

class ResistorColor { private colors: string[] public colorValues: {grey: number, white: number} = { grey: 8, white: 9 } } We can replace 'any' with a specific type to ensure proper typing in Typescript. How do we assign correct ...

Accessing elements within documents opened using the window.open method

My goal is to open a new browser window based on a provided URL using JavaScript's window.open function. However, my ultimate aim is to inspect the newly opened window and alter its URL to redirect to a different site. I attempted to achieve this with ...

Route Separation with ExpressJS and Socket.IO

As I delve into the world of ExpressJS and Socket.IO, I find myself facing a puzzling situation. My routes are neatly organized in a separate file that I include from my app.js: var express = require('express') , db = require('./db&ap ...

Ways to retrieve a file from a specific location using fetch/axios?

For my research, I need to utilize certain network APIs such as fetch or axios to access a local file without using the fs module or importing them directly. I attempted to use both fetch and axios but found that they do not support fetching local files, ...

Can JavaScript event listeners be compelled to trigger in a specific sequence?

Is there a way in JavaScript to receive notification or execute a callback function once an event has completed its propagation? Put differently, is it possible to 'prioritize' an event and ensure that it gets triggered after all other event lis ...

show tab focus outline only

In search of a straightforward and effective method for focusable elements to display an outline only when the tab key is pressed, without showing it when using a mouse in React applications. (looking for something similar to :focus-visible that function ...

Having trouble with Simplemodal showing link content in the modal window

Having trouble getting the modal window to display content from another link? I'm pretty sure I've connected them correctly using the right classes. This is the basic JavaScript provided by . jQuery(function ($) { // Load dialog on page load //$ ...

Dealing with the "TypeError: Cannot read property 'style' of undefined" error in material-ui Transitions: A troubleshooting guide

While attempting to incorporate transitions within my react app, I encountered a recurring error whenever I tried to implement any transition module: "TypeError: Cannot read property 'style' of undefined". (anonymous function) node_modules/ ...

Exploring the method to find all corresponding keys within deeply nested objects

Within my 'const', I have an array filled with objects. Each object contains a key called 'image' which holds the value for 'url' as illustrated below. const images =[ { "image": { "url& ...

The concatenation of Ajax results appears to append to the existing data

My ajax function handles uploading comments to a form, which then returns the same string. If successful, the comment is added to a comment box and the input text is cleared. The issue arises when a user adds another comment; the new comment is appended w ...

The Node.js application that uses Express and connects to a MSSQL database is reporting that the database

One of my other applications utilizes express and routes, but for this new app I wanted to simplify it. Despite being confident in the correctness of the connection string, I encountered an issue. script.getQuestions(connection); script.getQuestions = fu ...

Modify data in an array using Vuex

When working with my Vuex mutation, I am trying to replace an element in an array within the state. The code snippet below illustrates what I am attempting to do: UPDATE_MAILING(state, mailing) { let index = _.findIndex(state.mailings, {id: mailing.id ...

A JSON request is being processed within a while loop

Attempting to complete what I initially thought was a simple task has led me to believe that I may have oversimplified the process or made a mistake in my loop. My objective is to browse through a series of links containing JSON objects in order to identif ...

Creating a custom navigation bar that elegantly fades away with a smooth animation as you scroll down the page is a must-have

How can I create a navigation bar that disappears when scrolling, with a smooth animation? This is the progress I have made so far. HTML: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/style.css" type="tex ...

Developing a feature in React Native to retrieve the user's location without properly updating and returning the received data

In the function below, I am attempting to retrieve the user's current location and update specific location properties: export const getCurrentLocation = () => { const location = { userLat: '5', userLng: '' } navi ...