Retrieving decimal value from a given string

Currently, I am working with Google Maps and encountering an issue with distance values being returned as strings like 1,230.6 km. My goal is to extract the floating number 1230.6 from this string.

Below is my attempted solution:

var t = '1,234.04 km';
var a = t.replace(/[^0-9]/g, '') // 123404

parseFloat(t) // 1

Can anyone assist me in fixing this using Regex? Your guidance would be greatly appreciated.

Answer №1

To include the period . in your regular expression, you can use the following code:

var example = '1,234.04 miles';
var result = example.replace(/[^0-9.]/g, ''); // 1234.04

parseFloat(result); // 1234.04

Answer №2

Here are some steps you can take:

let distance = '1,234.04 km';
let cleanDistance = distance.replace(/[^0-9.]/g, '');
    
console.log(parseFloat(cleanDistance));

Answer №3

let distance = '1,234.04 km'.split(',').join(''); var regex = /[+-]?\d+(\.\d+)?/g; var numbers = distance.match(regex).map(function(val) { return parseFloat(val); }); console.log(+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

Guide on passing variables along the promise chain within a Node Express router

Upon reflection, I realized the difficulty of injecting or utilizing a variable inside the Promise scope without a surrounding object or a "this" reference to attach it to. ...

removing an item from a nested array through the use of the filter() method

I have been struggling to remove an element with a specific ID from a nested array. Are there any suggestions on how to effectively utilize the filter() method with nested arrays? The goal is to only eliminate the object with {id: 111,name: "A"}. Below ...

Height Setting for Angular Material Buttons

html: <body id="app"> <md-button> Yo </md-button> </body> Looks: Why is the button set to 100% height? It should look like an inline element according to the materials documentation here. Also, why aren't the materi ...

Trapped in the clutches of the 'Access-Control-Allow-Origin' snag in our Node.js application

Our nodeJS application is deployed on AWS Lambda, and we are encountering an authentication issue with CORS policy when trying to make a request. The error in the console states: Access to XMLHttpRequest at 'https://vklut41ib9.execute-api.ap-south-1 ...

AngularJS | Validate input values to ensure they fall within acceptable range for both arrow and user input types

I have a text input field where I need to limit the value between 1 and 20. Here is the HTML code snippet: <input type="number" class="form-control input-rounded" ng-model="Ctrl.new.runner" ng-change="Ctrl.newChangeAction(Ctrl.new)" ...

Is there a way to trigger a function from a specific div element and showcase the JSON data it retrieves in

I am working with a React JS code page that looks like this: import React, { useState } from "react"; import { Auth, API } from "aws-amplify"; function dailyFiles(props) { const [apiError502, setApiError502] = useState(false); // Extracted into a re ...

What makes ngFor unique in Angular that allows it to not require keys like in Vue and React?

I recently delved into learning Angular a few weeks back. In Vue and React, we typically use a unique key when rendering an array of elements to optimize the rendering process, especially when there are changes in the elements' order or quantity. As a ...

The return value of fs.mkdirSync is undefined

I'm facing a challenge with creating a directory and utilizing that directory as a variable to extract files from zip/rar files. The section of code that is causing an error is shown below: var fileZip = fileName.replace(/^.*[\\\/]/, ...

Accessing the session object within an Express middleware function is crucial for

This is my unique Express middleware setup: var app = express() .use(express.cookieParser()) .use(express.session({secret: 'HiddenSecret'})) .use(express.bodyParser()) .use(function displaySession(req, res, next) { consol ...

Tips for expanding AntD Table to show nested dataSource values

I need help dynamically rendering data into an antD expandable table. The data I have is a nested object with different properties - const values = [ [name = 'Josh', city = 'Sydney', pincode='10000'], [name = 'Mat ...

AutoComplete issues a warning in red when the value assigned to the useState hook it is associated with is altered

const [selectedCountry, setSelectedCountry] = useState(); <Autocomplete autoHighlight={true} //required autoSelect={true} id="geo-select-country" options={availableCountries} value={se ...

What is the best way to maintain the position of components (such as a Card component) when one is expanded in a Material-UI and ReactJS project

Currently, I am working with an expandable Card component from Material-UI and using flex for aligning the components. However, when one card expands, it affects the positioning of the other components in the row: https://i.stack.imgur.com/vGxBU.png What ...

Capture the selected hyperlink and show the corresponding page title in a designated box for reference

I want to track the links that users click on and display them in a box with an image and name of the page. Additionally, I would like to show how long the user spent on each page below the image. The images in the box should also be clickable links to the ...

Eliminating the 'white-space' surrounding concealed images

I am currently working on a project where I have a list of images that need to be hidden or shown based on the click event of specific <li> elements. While I have managed to achieve this functionality successfully, I am facing an issue with white spa ...

React navigator appears stuck and unable to navigate between screens

I encounter an issue where my app closes when I press the switch screen button, but there is no error output displayed. I have checked for any version discrepancies and found no problem. The function I implemented for the button is functioning as expected ...

Can a Typescript class type be defined without explicitly creating a JavaScript class?

I am exploring the idea of creating a specific class type for classes that possess certain properties. For example: class Cat { name = 'cat'; } class Dog { name = 'dog'; } type Animal = ???; function foo(AnimalClass: Animal) { ...

Click on the submenu to expand it, then simply select the desired option to navigate

I have created a toggle menu that displays a list of child elements when clicked, and hides them if clicked again. However, when a child element is clicked, I want it to navigate to the corresponding page. I am having trouble getting this functionality to ...

Are queued events in React discarded upon a state change?

As I develop a React form component with simple validation, I encounter an issue where the onBlur event of a field and the onSubmit function of the form are triggered simultaneously. If there is a change in the state during onBlur, the onSubmit function do ...

Can callback argument types be contingent on certain conditions? For example, could argument 0 be null if argument 1 is a string?

I am attempting to implement conditional type logic for the parameter types of a callback function. In this scenario, the first argument represents the value while the second argument could be an error message. type CallbackWithoutError = (value: string, ...

What is the reason for the malfunction of this JavaScript code designed for a simple canvas operation?

I'm having trouble with the code below. It's supposed to display a black box on the screen, but for some reason it's not working properly. The page is titled Chatroom so at least that part seems to be correct... <html> <head> &l ...