Using regular expressions in Javascript to extract decimal numbers from a string for mathematical operations

I'm currently working on a Vue method where I extract information from a WordPress database. The data retrieved sometimes contains unnecessary text that I want to filter out.

Using the prodInfo variable, the input data looks something like this: 2,5kg meal or 500g cookie

I find the regex I'm using to be cumbersome as it requires creating data with template literals. Is there a more efficient way to handle these calculations and extract the necessary information?

extractTotal(prodInfo, prodPrice, code){
  let val = prodInfo.match(/[0-9]/g)
  let multiplier
  if( val.length > 2 ){
    multiplier = `${val[0]}${val[1]}${val[2]}`
  } else if( val.length === 1 ) {
    multiplier = val[0]
  } else {
    multipier = `${val[0]}.${val[1]}`
  }

  if( multiplier === '500' ){
    return (parseFloat(prodPrice) * this.q[code] / 2)
  } else if( multiplier === '1' ) {
    return (parseFloat(prodPrice) * this.q[code] * 1)
  } else {
    return (parseFloat(prodPrice) * this.q[code] * multiplier)
  }

}

Answer №1

Try using this regular expression pattern: /[0-9]+\,?[0-9]*/g

You can then replace the , characters with .

// For example
const input = '2,5kg meal 500g cookie'
const floats = input
  .match(/[0-9]+\,?[0-9]*/g)
  .map(a => parseFloat(
    a.replace(',','.')
  )
)

// The array of floats will be [2.5, 500]

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

Tips for loading a webpage directly to the center instead of the top position

Is there a way to make the page open at a specific div halfway down the page instead of starting from the top? Here is an example: <div id="d1"> <div id="d2"> <div id="d3"> <div id="d4"> <div id="d5"> <div id="d6"> Do ...

The issue of sluggishness in Material-UI when expanding the menu is causing delays

Watch Video Having trouble with the behavior of the Menu opening and closing similar to this example. The text seems slow to change position. Any ideas why? This is the devDependencies configuration I am using in webpack. "devDependencies": { ...

React JS routes function properly only upon being reloaded

Encountering a problem with my reactJS routes where the URL changes in the address bar when clicking on a link, but the component does not render unless I refresh the page. Here is an excerpt from my code: index.js import React, { Component } from &apos ...

Encountered a TypeError with mongoose: The function specified is not recognized as a valid function when attempting to create a new mongoose instance

I'm currently developing a web application using the MEAN stack, and I've encountered an issue with my mongoose instance that's giving me a headache. Let me share parts of my code: my route const express = require('express'); co ...

Fix a typing issue with TypeScript on a coding assistant

I'm struggling with typing a helper function. I need to replace null values in an object with empty strings while preserving the key-value relationships in typescript // from { name: string | undefined url: string | null | undefined icon: ...

The jQuery AJAX autocomplete result box is either too cramped or displaying numbers

I'm having some trouble setting up jQuery UI autocomplete with ajax in my project using CI 3.1.5. When I try to implement it, I either get a small result box or just the number of results. Here is my AJAX code snippet: $(".addClient").each(funct ...

Tips for dynamically updating the id value while iterating through a class

Here's the HTML snippet I am working with: <div class="info"> <div class="form-group"> <label class="control-label col-sm-2">Title</label> <div class="col-xs-10 col-sm-8"> <inpu ...

The imgAreaSelect plugin is up and running successfully. Now, I am looking to utilize the x and y coordinates to make updates to the image stored in the database. How can I

After retrieving the dimensions and coordinates from the jQuery plugin imgAreaSelect, I am looking for guidance on how to update the image in my database based on this selection. The database contains a tempImage and Image field, and my goal is to allow ...

What is the best way to remove a property from an object in React if the key's value is set to false?

I'm currently working on a form component and I've encountered an issue. Whenever I submit the form, it returns an object with various fields such as email, fieldName1, fieldName2, first_name, last_name, and organization. Some of these fields are ...

Enhancing Watermark Functionality for Text Boxes

I am encountering an issue with three textboxes all having watermarks. When I use JavaScript to set the value of the second textbox in the OnChange event of the first textbox, the text appears as a watermark. However, when I click on the textbox, it become ...

Mastering the art of switching between different application statuses in ReactJS

As a newcomer to reactJS, I am exploring ways to make one of my components cycle through various CRUD states (creating object, listing objects, updating objects, deleting objects). Each state will correspond to displaying the appropriate form... I have co ...

The process of implementing web-based online diagramming software involves a strategic approach to designing and integrating various

I'm really interested in learning how web-based online diagramming software works. If anyone could provide guidance or point me to example resources, I would greatly appreciate it. Here are some of the web-based online tools that I have been explorin ...

Custom template for label in Vue 2 select2 framework

Is it possible to customize the label slot in a similar way to how we can change the template for the option slot in Vue Select? <v-select inputId="originsId" :options="origins" label="city" placeholder="Search..."> <template slot="option" ...

The caching mechanism in IE 11 is preventing Ajax from loading and displaying data

Utilizing Ajax to verify data and display it on the page, alongside implementing varnish cache. The data appears correctly on all web browsers, with the exception of IE 11, unless the varnish cache is disabled. function checkMyData() { var surl = 'in ...

The VueJS component fails to load on the webpage

Here is my Vue.js component code that I am having trouble with. Despite its simplicity, it does not load correctly: Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: { msg: 'hello' ...

Developing Webpart Postback logic in C# script

I am currently facing challenges with SharePoint webparts programming. I am unsure about how to trigger a postback for an object at a specific time. I have come across suggestions to use "javascript" for this purpose, but I am having trouble understanding ...

What could be the reason for my array parameter not being included in the POST request

When working on my laravel 5.7 / jquery 3 app, I encountered an issue while trying to save an array of data. After submitting the form, I noticed that only the _token parameter is being sent in the POST request as seen in the browser console: let todos_co ...

What is the best way to conceal a dropdown menu when the page first loads?

I have a dropdown menu that is displaying like this: <ul> <li class="dropdown open"> <a aria-expanded="true" href="#" class="dropdown-toggle waves-effect waves-button waves-classic" data-toggle="dropdown"> <spa ...

What is the best method for directing to various pages on a GitHub Pages website?

My GitHub Pages site is live at this link. While the splash page loads perfectly, clicking on the circle to transition to the next page, 'landing.html', leads to a 404 error. I have exhausted all possible solutions to address this issue, includin ...

Exploring the integration of Styled-components in NextJs13 for server-side rendering

ERROR MESSAGE: The server encountered an error. The specific error message is: TypeError: createContext only works in Client Components. To resolve this issue, add the "use client" directive at the top of the file. More information can be found here i ...