Adding values separated by semicolons in JavaScript

I am facing an issue with a column named priclmdetailli55 in a file. This column can have no value, one value, or two values separated by a semicolon. I want to sum the values if they are separated by a semicolon.

This is my current approach:

 var str = priclmdetailli55;
        var1 = str.substring(0,str.indexOf(";") );
        var2 = str.substring(str.indexOf(";") + 1, str.length + 1);

        var1 = var1.replace(",", "");
        var2 = var2.replace(",", "");


        var var3 = parseint(var1) + parseint(var2); 

{var var3}

Unfortunately, when I use this code, the column turns out to be blank. I would appreciate any tips or insights on how to fix this problem.

Answer №1

It appears that your syntax may not be quite right. To address numbers with commas, such as 10,000, a simple regex can be used.

Referencing advice from adeneo, the code below is provided to handle numbers with or without commas:

var str = "10;15;20";
var sum = str.split(';').reduce((a, b) => parseInt(("" + a).replace(/,/g , "")) + parseInt(("" + b).replace(/,/g , "")));
console.log(sum);

str = "10,200;15,500;20,100";
sum = str.split(';').reduce((a, b) => parseInt(("" + a).replace(/,/g , "")) + parseInt(("" + b).replace(/,/g , "")));
console.log(sum);

This code functions in the following manner:

  1. Splits the string by ;.
  2. Removes the , from each number.
  3. Adds using an accumulator.
  4. Returns the sum of numbers.

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

Load a partial view in MVC using Ajax with a complex data structure

Within my main view, I have a section that loads a partial view containing data. Here is the code snippet that is executed upon initial loading: <div id="customerdetailsDIV" class="well main-well clearfix"> @Html.Partial("_customer_details", Mod ...

Group all 3 elements with a wrapper

I'm facing a challenge in trying to enclose 3 divs inside one wrapping div. I have successfully wrapped up 2 divs, but the third one is proving to be difficult. To see my progress so far, you can check out my JSFiddle here: http://jsfiddle.net/cz9eY/ ...

What is the best way to apply typography theme defaults to standard tags using Material-UI?

After reading the documentation on https://material-ui.com/style/typography/ and loading the Roboto font, I expected a simple component like this: const theme = createMuiTheme(); const App = () => { return ( <MuiThemeProvider theme={theme}> ...

Iterating over images and displaying them in Laravel's blade templating engine, updating outdated Angular code

Currently, I am in the process of transitioning an Angular repeat function used for displaying images on our website (built with Laravel). The goal is to eliminate Angular completely and handle everything using Laravel loops in the blade template. I have ...

Ways to transmit information to the frontend JavaScript of one server from a different server

In my express js app, I have set up two routes as follows: router.get('/route', function (req, res) { res.redirect('/newRoute'); }); router.get('/newRoute', function (req, res) { var data = someCalculation(); }); I a ...

Customize the yellow background color of Safari's autofill feature by following these simple

When I open this image in Safari, this is what I see: https://i.stack.imgur.com/KbyGP.png However, this is the code I have: https://i.stack.imgur.com/4wEf0.png References: How to Remove WebKit's Banana-Yellow Autofill Background Remove forced ye ...

Display a dynamic variable within React's HTML code

const fetchTime = () => { const currentDate = new Date(); const currentTime = currentDate + ' ' + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); return {currentTime}; } export default fun ...

What could be the issue with the nodeValue property?

// html <div>Welcome Everyone!</div> // JavaScript var textElement = div.firstChild; textElement.nodeValue = "Hello Everyone"; Here is the example: example Why is it not possible to modify the text content? ...

The progress bar in Java Script is static and cannot be customized to change colors

Trying to use HTML for image uploads and I've created Java code to monitor the progress of the upload. However, I'm facing an issue where I cannot change the color of the progress loading bar. Below is the code I am currently using for uploading ...

What is the process for configuring sendmail in a node.js environment?

After setting up Sendmail on my Nginx server and configuring SMTP for sending emails in my Node.js project, I still encountered issues with emails not being sent. I tried using Sendmail directly, but I'm unsure of how to properly configure it. Here i ...

What is the best way to track all method calls in a node.js application without cluttering the code with debug statements

How can I automatically log the user_id and method name of every method called within a javascript class without adding logger statements to each method? This would allow me to easily track and grep for individual user activity like in the example below: ...

Trouble with the combining of values

Here is a function I have created: function GetCompleteAddress() { $('#<%=txtAddress.ClientID %>').val($('#<%=txtWhere.ClientID %>').val() + ', ' + $('#<%=txtCity.ClientID %>').val() + &apo ...

Struggling to retrieve variable values for dynamically generating a form using JavaScript

The form will be created in this HTML file within a "div" with the ID of "form". The variables are defined within the HTML file. <body> <script> var types=['text','number', 'text']; var fields ...

Access to property 'nodeType' on AJAX request in Firefox has been denied due to permission error

On my webpage, I have integrated the Google Sign-in button along with gapi for interaction. After a successful authentication using the Google API, an AJAX call is made to the server using JQuery: var token = gapi.auth.getToken(); var data = { "to ...

Nextjs is not updating the Redux api state

I am working on a vehicle form component where users can select the year, make, and model of their vehicle. When a user selects the year, I trigger a Redux action to fetch all makes for that specific year. Subsequently, when the user selects a make, anothe ...

Unable to successfully add a property to an object within a collection managed by Sequelize

While working on a code similar to this one, I encountered an issue where adding a property doesn't work as expected. router.get('/', async (req, res, next) => { let produtos = await produto.findAll(); for(let i = 0; i < pro ...

Smoothly animate a Three.js object in response to an event without changing its current position

I need assistance with slowing down the rotation animation of a cube when a mouse hovers over it and making it continue smoothly on mouse leave. The current issue I'm facing is that when the mouse enters the cube, the rotation slows down but abruptly ...

What is the best way to convert a requested JSON array into a CSV file using Python?

I'm completely new to programming and I'm having trouble saving my data. Currently, I'm working on a website for a scientific experiment where users are required to click 'yes' or 'no' buttons to indicate their recognitio ...

The Google Maps JavaScript API is displaying a map of China instead of the intended location

After multiple attempts, I am still facing an issue with setting up the Google Map on my website. Despite inputting different coordinates, it consistently shows a location in China instead of the intended one. Here is the code snippet that I have been usin ...

JavaScript Intercept Paste function allows you to detect and capture data being past

I stumbled upon this code snippet while browsing through how to intercept paste event in JavaScript. The code works well for intercepting clipboard data before it's pasted, ensuring that essential "\n" characters are not lost during the process. ...