Eliminating commas from text except when they are enclosed within quotation marks, without employing

Trying to eliminate commas from a string, except when they are enclosed in quotes.

var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';

mystring = mystring.split(',').join(newchar);// working correctly


document.write(mystring);

The output I currently have is:

this is a test example "i dont know" jumps

The expected output should be:

this is a test example "i, dont know" jumps

I have a few questions. How do I determine the index of a string so that commas are included inside quotation marks but not outside of them? I believe I need to use indexOf and substring, but I am unsure about the formatting. (Please avoid using regex as I am new to JavaScript and focusing on the fundamentals.)

Answer №1

To solve this problem, iterate through the given string while keeping track of whether you are currently inside a pair of quotation marks. As you loop through, create a new string where commas within quotes are not included:

let withinQuotation = false;              // Are we currently inside quotes?
let resultString = '';                     // Initialize the new string.

for (let index = 0; index < input.length; index++) {      // Iterate through the string.
  let character = input[index];            // Get the current character.
  let isComma = character === ',';         // Check if it's a comma.
  let isQuote = character === '"';         // Check if it's a quote.

  if (withinQuotation || !isComma) {       // Should we include this character?
    if (isQuote) withinQuotation = !withinQuotation;     // Toggle quotation status if it's a quote.
    resultString += character;             // Add the character to the result string.
  }
}

This alternative solution excels in handling cases with multiple quoted strings within the input compared to the original technique.

Answer №2

While this code may be effective in certain situations, it may not be suitable for all scenarios. For instance, it cannot handle strings containing more than two quotation marks.

var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '';
var firstIndex = mystring.indexOf("\"");
var lastIndex = mystring.lastIndexOf("\"");
var substring1 = mystring.substring(0,firstIndex).split(',').join(newchar);
var substring2 = mystring.substring(lastIndex).split(',').join(newchar);
mystring = substring1 + mystring.substring(firstIndex, lastIndex) + substring2;

document.write(mystring);

Answer №3

One day you'll discover the power of using regular expressions, and that's when regexr.com will become your best friend. The solution with regular expressions is quite straightforward:

var mystring = "this, is, a, test, example, \"i, dont know\", jumps" ;
var newchar = '_';

mystring = mystring.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g).join(newchar);// working correctly

document.write(mystring);

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

Conflicting Joomla Modules

I'm currently working on a project at the following link: www.eltotaldesign.com/planeteco Within this project, I have integrated the modules DJ Image Slider and Altra Switcher. Despite attempting to install Easy JQuery and other methods, I have been ...

Print out the data on the webpage that was sent via AJAX

I am currently working on a project where I need to create a web page that takes a number as input and searches for its corresponding name in the database. The challenge is to display the name on the page without reloading it. However, the problem is tha ...

Is there a different option available in place of the JavaScript confirm function?

I developed an application where I heavily utilized the javascript confirm function. confirm("Do you want to proceed"); However, I am not satisfied with the default appearance of the confirm dialog and would like to implement a customized version with be ...

Pair a specific portion of text with another string

I'm having trouble finding a substring within a string. The substring and the string are as follows: var str="My name is foo.I have bag(s)" var substr="I have bag(s)" When I use str.match(substr), it returns null, probably because the match() funct ...

Incorporate a personalized array into Google Autocomplete Places using AngularJS

I'm working on my application and I've implemented autocomplete for Google Places using the gm-places-autocomplete directive. However, I would like to enhance this autocomplete feature by incorporating my custom array of locations along with the ...

Creating a dynamic loader with JavaScript and PHP: A step-by-step guide

Currently focused on PHP development, my task involves retrieving data from a database using multiple queries. The database may contain anywhere from 10 records to 10,000 records. I am looking for a way to incorporate a progress bar that displays the com ...

Storing multiple values of dynamically added elements in a single variable and accessing them within a function

Is it possible to store multiple values into a single variable and then access them in a setTimeout function? $(document).ready(function (){ div ({'div':'#noo','auto':'true','pos':'top',' ...

Extract values from a JSON array to populate a select list with ID and Value pairs

I appreciate your help. I have now passed in the array as JSON and set the datatype to json, following your example like this: {"car_make_id":"3","car_engine_type":"Non-Turbo Petrol"}{"car_make_id":"3","car_engine_type":"Non-Turbo Diesel"} However, my sc ...

Challenges with jQuery Form validation and submitting entries

I am having some issues with my form validation using jQuery. The current setup is working well, but I need to make a specific change that I am struggling with due to my limited knowledge of jQuery. I want to ensure that text boxes, such as first name an ...

Tips for Automatically Loading Dependencies in AngularJS

Currently, I am working on an Angular application where I am designing various widgets using HTML5. Here is a snippet of the code structure: <html ng-app> <div ng-controller="widget1"> </div> <div ng-controller="widget2"> ...

Mapping object data within an object in React: A step-by-step guide

Within my React project, I am retrieving data from a JSON source like so: https://i.sstatic.net/fEZFL.jpg The simplified JSON data appears as: const listData = [ { "_id": "abscdf456", "bucket": { code: "videos" }, "contents": [{}, {} ...

An easy guide to creating a JavaScript function to locate books written by authors with less than 4 characters

Need assistance! Trying to figure out how to create a function that locates books with an author name containing less than 4 characters. const books = [ { "id": "a5b16ad1bb2e96b8c649da7150ad5726", "t ...

Utilize or Bring in an external JavaScript file within Ionic 2

Currently working with Ionic 2 and Typescript Angular 2 and facing an issue. I need to utilize an external JavaScript file located at . How can I import or include this in my project? ...

Successful response from WordPress AJAX

I am currently working on setting up a contact form in WordPress using wp_mail along with Ajax. The email functionality is working fine, but I am facing some issues with the success response from Ajax. After sending the email, I want to display a message ...

Elegant Decline of Javascript Functionality - Imported Web Assets

Looking for assistance from experienced JS coders. I'm currently working on a Wordpress website that utilizes jQuery AJAX methods to reload either the entire content area or just the main content section based on different navigation clicks. My aim i ...

Could one achieve the task without the presence of a function?

When I execute the below code: let app = express() in the console, it outputs: { [EventEmitter: app] _events: { mount: [Function: onmount] }, _eventsCount: 1, _maxListeners: undefined, setMaxListeners: [Function: setMaxListeners], getMaxList ...

Encountering a Vercel deployment failure due to a TypeError: The 'split' property cannot be read from undefined within several objects

I'm having trouble deploying my web application for the first time and encountering this error on Vercel: TypeError: Cannot read property 'split' of undefined at Object.3qS3 (/vercel/path0/.next/serverless/pages/[collection]/[templateId].j ...

Senecajs responded with a result that was neither an object nor an array, displaying a Promise

Seeking guidance on incorporating promises into my Seneca modules. Firstly, there is the server.js file that exposes a route: var express = require('express'); var app = express(); var Promise = require('bluebird'); var seneca = requ ...

Switching videos dynamically with JavaScript while utilizing Bootstrap to enable playback in a floating window

This is a piece of code that enables playing videos in floating windows using Bootstrap. However, I am looking to enhance the functionality by dynamically changing the video source using JavaScript. I tried using onClick() to modify the src attribute of th ...

Typedoc encountering an issue due to the require syntax

I am currently attempting to create documentation using typedoc. The lines in my typescript file are as follows: var validator: any = require('validator'); import * as _ from 'lodash'; var mqtt: any = require('mqtt'); var fs ...