Import and parse a CSV file using JavaScript

Having trouble uploading a CSV file to my database using PHP. I encountered issues with the numbers, leading me to import the file into an array using JavaScript. Upon importing, I noticed that the numbers in the CSV are appearing differently. For example, the number 23447 is displayed as "23 447" (including spaces and quotes). How can I modify my code to properly format the numbers?

https://i.sstatic.net/JIdsG.png

https://i.sstatic.net/sN29q.png

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#upload").bind("click", function () {
            var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
            if (regex.test($("#fileUpload").val().toLowerCase())) {
                if (typeof (FileReader) != "undefined") {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var table = $("<table />");
                        var rows = e.target.result.split("\n");
                        for (var i = 0; i < rows.length; i++) {
                            var row = $("<tr />");
                            var cells = rows[i].split(",");
                            if (cells.length > 1) {
                                for (var j = 0; j < cells.length; j++) {
                                    var cell = $("<td />");
                                    cell.html(cells[j]);
                                    row.append(cell);
                                }
                                table.append(row);
                            }
                        }
                        $("#dvCSV").html('');
                        $("#dvCSV").append(table);
                    }
                    reader.readAsText($("#fileUpload")[0].files[0]);
                } else {
                    alert("This browser does not support HTML5.");
                }
            } else {
                alert("Please upload a valid CSV file.");
            }
        });
    });
</script>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" />
<hr />
<div id="dvCSV">
</div>

Answer №1

To transform the csv cell values, simply remove all spaces (whitespace characters can be matched using the regex special character \s) and then convert to a number. Use the following function to achieve this for each value:

const processNumber = str => {
  const strWithoutSpaces = str.replace(/\s*/g, '');
  const numberFromStr = +strWithoutSpaces;
  return numberFromStr;
}

console.log(['10 000', '3 000 000', '100'].map(processNumber))

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

Creating custom validation in Vuetify for password confirmation is essential in ensuring that

While developing a Vue.js template, I encountered a scenario on the sign-up page where I needed to compare passwords during user registration. To achieve this, I implemented a custom validation rule in the code snippet below: <v-text-field label=" ...

Validating passwords using Vuetify

I am implementing password validation on my form using Vuetify validation rules: passwordRules: [ v => (v && v.length >= 1 && v.length <= 10) || 'Password length should be between 1 and 10', v => (v && v.l ...

What could be causing the JSON.stringify() replacer function to fail?

Here is the code snippet I'm working with: http://jsfiddle.net/8tAyu/7/ var data = { "foundation": "Mozilla", "model": "box", "week": 45, "transport": { "week": 3 }, "month": 7 }; console.log(JSON.stringify(data, ...

Tips for displaying complex JSON structures in VueJS

I want to extract this information from a JSON dataset <ol class="dd-list simple_with_drop vertical contract_main"> <li class="alert mar" data-id="1" data-name="Active" style=""> <div class="dd-handle state-main">Active<span cl ...

clicking on a DIV element

I am trying to trigger a JavaScript function by clicking on a DIV element, but for some reason it is not working as expected. I have gone through various examples provided by the helpful people here, but still can't figure out what I'm doing wron ...

What are the best strategies for handling complex task operations in Node.js Express.js?

How can I effectively manage lengthy task functions in Node.js Express.js to prevent timeout errors? Currently, my application includes a time-consuming function that does not require an immediate response but still needs to execute its tasks. How can I en ...

The jQuery functionality is not functioning properly within the aspx file

I came across some JavaScript code on stackoverflow that is not working in my own code, but strangely it works perfectly fine in the jsFiddle: https://jsfiddle.net/rxLg0bo4/9/ Here is how I am using inline jQuery in my code: <nav id="menu"> < ...

Receiving an alert in VSCode regarding the usage of CharAt function in conjunction with Vuejs

While attempting to extract the first character of a computed property, I utilized the charAt() function. Despite the fact that it is functioning correctly, I am receiving a warning from VSCode indicating that it is not the correct usage. computed: { ...m ...

Iterating recursively through a tree structure to update properties using Mongoose

I have a unique structure resembling a tree that I've set up to store comments. Each "comment" acts as a node with a "parent" property linking it to another "comment" node. Additionally, I've included a "replyCount" field on each node to keep tra ...

Surprising outcomes encountered while attempting to load a text file into an array with JavaScript

Currently, I am in the process of developing an emulator and seeking to compare opcode logs from another functional emulator. The log containing executed opcodes is prepared for comparison and follows this format: //log.txt (10000 lines long) 0 195 33 195 ...

What is the most efficient way to retrieve the operating system's name and version using JavaScript?

I'm in the process of developing an object that will simplify accessing browser and system information by implementing a function. One particular function within this object is responsible for retrieving the operating system name and version, returnin ...

Is there a "hasContent" function available in webdriverjs?

Currently, I am exploring the use of webdriverjs for testing purposes and I am really enjoying the experience so far. However, I have encountered a challenge while attempting to run more general tests. I am wondering if there is a way to check if a webpage ...

Experiencing difficulty retrieving individual :id information from a list in MEAN stack

**I'm experiencing issues retrieving a single :id from a list as the data returned is not what I expected... ** GET /article/5b0be8829f734a4e580a43c5 401 3.845 ms - 99 ===> response from my get request my api ===> var express = require ...

inserting a for-loop inside a div tag

I've created a script that modifies the background color and plays a sound in response to user input. The changes are triggered by the length of the input provided. Additionally, I have a div element where I aim to display the specific letter causing ...

Trouble with minification in Sencha cmd 5

I've been attempting to compress a Sencha 5 project using Sencha CMD, but I keep experiencing failures. sencha generate app -ext demoApp ./demoApp Then, in an effort to compress the application, I entered the following command: sencha app build ...

Using a JSON key as a parameter in a function

Would it be achievable to specify the key of an object as a function parameter? For instance, if I were to develop a filter function that could sort multiple map markers by marker.element.country or marker.element.population? This approach would allow me ...

The combination of WASM and Node.js encounters an issue when attempting to utilize 'import.meta' outside of a module

I successfully compiled the FastText C++ module to a wasm module using the provided make file, with the following flags: EMCXX = em++ EMCXXFLAGS = --bind --std=c++11 -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -s "EXTRA_EXPORTED_RUNTIME_METHODS=['addOnPos ...

Using jQuery to upload files and send additional form data

When users upload a PDF file, I need to include additional data in the database. There are two radio buttons for selecting the type of document. How can I store the 'doctype' along with the uploaded file in the database? I have gone through the f ...

Align list items in the center horizontally regardless of the width

I have created this container element: export const Container = styled.section<ContainerProps>` display: flex; justify-content: center; `; The current setup is vertically centering three list items within the container. However, I am now looking ...

Guide to resetting all ReactiveVars to false in Meteor JS

I am currently working on a recipe template where I am using {{#each recipes}} to render the recipes. I have implemented ReactiveVar to toggle the edit form of each recipe from hide to show. Everything is functioning correctly, but I want to ensure that ...