Locate commas within quotation marks using regex and replace them with their corresponding HTML entity

When dealing with a string like this:

"Hello, Tim"

Land of the free, and home of the brave

I want it to be transformed into:

"Hello, Tim"

Land of the free, and home of the brave

This should be a simple task, but I'm struggling to find the solution. I am trying to import a corrupted CSV file with thousands of entries using AJAX, and I need to convert commas that are inside double quotes.

How can I achieve this using JavaScript? I've attempted

Answer №1

let message = '"Hello, Tim"\n\
\n\
Land of the free, and home of the brave';

message
.split('"')
.map(function(value,index){ return index%2===0 ? value : value.replace(',',','); })
.join('"');

Visit MDC for a guide on how to use map() in browsers that do not support it.

Answer №2

To simplify the process, consider using a callback function for the replace operation:

text = text.replace(/"[^"]*"/g, function(match){return match.replace(/,/g,',');});

In the initial phase, identify all occurrences of quotes and only replace commas within them.

An option is to account for escaped quotes:

  • CSV format (with two double quotes) - /"([^"]|"")*"/g
  • String literal format - /"([^"\\]|\\.)*"/g

Answer №3

If you have the variable html with the string above, you can utilize the following script:

var n = html.match(/"[\s\S]*"/);
html = html.replace(n[0], n[0].replace(/,/g, ','));

RESULT

"Hello, Tim"

Land of the free, and the land of the brave

Answer №4

result = content.replace(/("[^"]+?),([^"]*?")/img, "$1,$2");

While this solution works well for most scenarios, it may fail if there are multiple instances of , within the same pair of ". If you encounter such cases, you can refer to this for a more robust method to parse CSV data using javascript.

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

Is there a way to display the next/previous buttons separately from the scroller in my jQuery thumbnail scroller implementation?

Is there a method to display the next and previous buttons outside of the scroller frame when using jQuery thumbnail scroller by manos.malihu.gr? I have attempted to modify the button class in CSS to make them more prominent or visible, but unfortunately ...

When using the Infinite Scroll React component, only a single new set of objects is loaded as you scroll down, and the loading

My React component is designed to load 6 images at a time as the page is scrolled down, creating an infinite scroll effect similar to what YouTube and Reddit now use. Currently, when the page loads, it shows the initial 6 images correctly. However, as I c ...

The placement of the breadcrumb trail is not in the right position

My website includes a menu and breadcrumbs. The menu consists of two submenus: Design Services, Design Portfolio, Design Fees, About Us, Contact Us, Design Resources, Design Vacancies, and Terms. Clicking on Design Services reveals Graphic Design, Logo Des ...

Jquery Delay feature failing to perform as desired

Afternoon all! Having a bit of trouble with a dialog box that I'm trying to close after a 5-second delay. Been tinkering with some code, but for some reason, the dialog box just closes right away without any delay. Here's the snippet I've ...

having trouble installing vue on macOS using npm

Here are the steps you should follow: Instead of using node v14+, switch to node v10+. (IMPORTANT) Add the following paths to your ~/.zshrc file (if you use zsh): /Users/[yourUsername]/.npm-packages/bin /Users/[yourUsername]/.npm-global/bin After ...

Retrieve the child scope of ng-repeat beyond the ng-repeat iteration and establish a two-way data binding

With my ng-repeat, I am attempting to include ng-model inside each repeated li, followed by two-way data binding outside of the ng-repeat. You can see the example in this jsbin: http://jsbin.com/yutinifivi/edit?html,js,output I have searched extensively f ...

Create a PHP form that includes a dropdown menu for selecting the quantity, allowing users to insert multiple rows of data inputted into the form

My first time posting something here. The issue I'm facing is: I have an HTML form with various variables. A dropdown for Quantity that should insert the data into a MySQL table multiple times based on the chosen quantity. For example, if the dropd ...

Transmit a pair of data values to the ajax request

How can I send two parameters to my JavaScript and retrieve them in a PHP file? Here is my HTML: <form method="post" action="testButtonSup.php"> <p> Please choose the service:<br /> <input type="radio" n ...

Utilize Vue to access and read a file stored in the current directory

I am attempting to retrieve data from a text file that is located in the same directory as my .vue file. Unfortunately, I am encountering an issue where the content of the text file is not being displayed in both Chrome and Firefox. Instead, I am seeing th ...

What is the process for activating my redux function within a component?

I'm working on a form that should create a new user when submitted. In my handleCreate function, I want to use Redux to trigger the addUser action and update the state to add the new user. However, it seems like I'm having trouble calling the act ...

Encountering the "TypeError: document.getElementById(...) is null" error message while utilizing react.js in conjunction with chart.js

I am encountering an issue while using react and chart.js together to create a bar chart. The problem lies in the fact that chart.js requires the use of canvas tags, and we need to locate this tag and insert the bar chart within it using the traditional do ...

JavaScript implementation of a carousel slider with responsive design

I have successfully implemented a feature carousel slider using the jquery.featured.carousel.js file along with some CSS. Here is the jsfiddle link to my project: LINK. When running this code on localhost, I noticed that I need to refresh the page every ...

Guide on extracting the text from the <script> tag using python

I'm attempting to extract the script element content from a generic website using Selenium. <script>...</script> . url = 'https://unminify.com/' browser.get(url) elements = browser.find_elements_by_xpath('/html/body/script[ ...

How can I use jQuery to create a new div element if it is not already present

I am familiar with how to add a class if it does not already exist, for example: $("ul:not([class~='bbox'])").addClass("bbox"); Alternatively, if(!$("ul").hasClass("class-name")){ $("ul").addClass("bbox"); } However, I am unsure how to c ...

Utilizing Vue.js to apply conditional statements or filters on v-for generated outputs

Currently, I am working on organizing my results by category. I believe there is room for improvement in the way it's being done: <div><h2>Gloves</h2></div> <div v-for="stash in stashes" :key="stash.id"> <div v-for= ...

How can you personalize a website script by deactivating it using uBlock Origin and then reintegrating it as a userscript?

Can you imagine if it were possible to address a problematic portion of a script on a website by preventing the original script from loading, copying the source code, editing it, and then re-injecting it as a userscript with Tampermonkey? I attempted this ...

From JSON to JavaScript transformations

Currently, I am attempting to utilize JSON with data retrieved from the server by implementing this PHP script: include("db_connect.php"); mysql_connect($host,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $resu ...

Issues with JavaScript causing YouTube embed player to malfunction

For the past few days, I've encountered an issue where my JavaScript code to embed YouTube videos isn't working properly. The video loads but it's not playable as the play button is unresponsive. The console shows this error: Uncaught TypeE ...

Allow the words to seamlessly transition back and forth between columns in a continuous cycle

Currently, I am attempting to showcase a large text in a format similar to a book. Each "page" has designated width and height, with content displayed over two columns: left and right. In this layout, page 1 is on the left, page 2 on the right, page 3 on t ...

What is the best way to find the vertex positions of a JSON model in

Here is the code I am using to load a 3D model in THREE.js: var noisenormalmap = THREE.ImageUtils.loadTexture( "obj/jgd/noisenormalmap.png" ); noisenormalmap.wrapS = THREE.RepeatWrapping; noisenormalmap.wrapT = THREE.RepeatWrapping; noisenormalmap.repeat. ...