Employing parseFloat() and parseInt() functions together with regular expressions in JavaScript for converting a Comma Separated Values (CSV

I've been working on converting a CSV file to a local 2D array and I'm curious if there's a more efficient method of changing strings to floats/int rather than relying on regex paired with parseFloat() / parseInt.

Any bright ideas or suggestions?

// numex() - checks if the string (str) is a number
// returns number.valid (true||false) and number.value = (float||int||string)
numex = function(str){
  number = {};
  number.valid = false;
  number.value = str;
  // determine if it's a number, then convert it to a float or int
  if((number.value.search(/[^0-9^\.^\$^\%^\-^\"^,^ ]+/) < 0) && str.length > 0) {  
    number.valid = true;
    number.value = str.replace(/[^\-^0-9^\.]+/g, ''); // TODO add % conversion code e.g. replace 10% with .1
    if(number.value.search(/[\.]/) >= 0) {  
       number.value = parseFloat(number.value); // replace floating point
    } else {
       number.value = parseInt(number.value); // replace integers
    }
  }
  return number; // number.valid = true or false;
}

var num = numex("1.101");
alert(num.value);

Answer №1

Instead of using regular expressions, consider the following approach:

let numberObj = {};  
numberObj.value = new Number(inputString);  
numberObj.valid = !isNaN(numberObj.value);

The Number constructor is stricter than parseInt and parseFloat as it does not accept strings like 10aaa or 1.2bbb, eliminating the need for a regex check.

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

NodeJS Socket not transmitting file after connection with client

Having scoured the depths of various resources, including SO and Google, I have hit a roadblock. I am struggling to understand why the socket is failing to capture the uploaded file via the form; it simply stops after connecting. When I check the console, ...

When utilizing the File System Access API, the createWritable() method functions perfectly within the console environment but encounters issues when executed

I've been diving into the File System Access API for an upcoming project and I'm struggling with using the createWritable() method. Specifically, I'm encountering issues with this line of code: const writable = await fileHandle.createWritab ...

Leveraging props to set the initial value of component data in Vue 3 Composition API

Currently, I am in the process of developing a search page in Vue 3 using the composition API. One of my components is responsible for displaying a snippet of data that includes specific keywords provided by the parent component. To achieve this, I need to ...

Issue with Highcharts: The useHTML flag is not functioning properly when trying to render labels

Currently, I am utilizing highcharts and a phantomjs server for rendering charts and labels. However, I have encountered an issue where the useHTML flag does not function as expected when rendering the labels. Following the instructions in the documentatio ...

Iview Table UI Cell

Is there a way to retrieve the cell data from a library iview table in Vue.js upon clicking? I am looking to capture both the value of the cell and the title of the column, and then modify the CSS of that particular cell. For instance, clicking on one ce ...

A step-by-step guide on revealing a complete div upon selection

Can anyone assist me in showing a div with a form inside it whenever a specific option is selected from a tag? Here is the code I currently have: <script type="text/javascript"> $(function() { $('#contactOptionSelect&apo ...

"Combining AngularJS with Material Design disrupts the functionality of infinite scroll

Issue: Infinite scroll is loading all pages at once instead of waiting for the user to scroll to the page bottom. Environment: AngularJS 1.3.17 Materials Design 0.10.0 Infinite scroll script: https://github.com/sroze/ngInfiniteScroll Demo being used: The ...

Implementing Othello Minimax Algorithm in React.js Yields Unsuccessful Results

I need assistance with a recurring issue where the AI player consistently plays the first available move it encounters. My objective was to implement an AI using the Minimax Algorithm, but I'm facing challenges in achieving the desired functionality. ...

Tips on accessing a function or variable within a script executed using $.getScript

After running a script with $.getScript, is there a way to access the namespace of that script? I expected to be able to do so since the plugin function is defined in the global scope. index.js $.getScript('plugin.js').then((...result) => co ...

The "Key" function from Object.keys does not yield true when compared to an identical string

Object.keys(data).forEach((key) => { bannerData[key] = data[key][0]; console.log(key); if (key == "timestamp") { labels.push(data[key]); console.log("wtf"); console.log(labels); ...

Meteor, enhanced with the dynamic Iron Router module and integrated

I am working on a project using Meteor (Meteor.com) and I want to incorporate iron-router for the page routing along with the pre-existing accounts-ui package for login functionality. Previously, my {{loginButtons}} functioned properly, but ever since I i ...

Divide a JavaScript project into multiple packages using either webpack or npm

I am embarking on the development of an application that needs to be compatible with Windows (PC), Android, and iOS. To achieve this, I plan to use Electron for Windows and React Native for mobile platforms. Both applications will be built using React and ...

React Navigation Bar Links Fail to Show Content

I'm a beginner in the world of React and I could really use some assistance. Right now, I am working on creating a portfolio using React and focusing on the Nav component. Although I haven't encountered any errors in the Console, when I click on ...

Tips for manipulating specific URL redirection to an alternative URL within a NuxtJs application

Take this scenario, where the inputted URL is: http://localhost:3000/course-details The desired outcome should be a redirection to http://localhost:3000/courses I recall there being a method for achieving this, but it slips my mind at the moment. ...

What steps can be taken to solve the JavaScript error provided below?

My objective is to create a new variable called theRightSide that points to the right side div. var theRightSide = document.getElementById("rightSide"); Once all the images are added to the leftSide div, I need to use cloneNode(true) to copy the left ...

Challenges with loading content on the initial page load using the HTML5

Upon page load, I wanted to save the initial page information so that I could access it when navigating back from subsequent pages. (Initial Page -> Page2 -> Initial Page) After some trial and error, I ended up storing a global variable named first ...

Achieve text length that does not exceed the specified limit dynamically

Is it possible to determine the length of the visible portion of text that overflows (or calculate the size of the overflow for further processing) using CSS or JavaScript? If so, can this calculation be done dynamically (such as on window resize)? The g ...

Scrolling automatically

I'm experimenting with creating a typing effect using JavaScript and the typed.js library, found here: My approach involves using a div as a container. However, I've encountered an issue - when the text reaches the height of the div, scroll bars ...

What is the best way to ensure that a React app is always displayed in full screen

I am facing an issue while developing an app with React and Material UI. I am trying to display the app in full-page mode, but unable to achieve it successfully. Currently, it appears like this: Here is my code snippet from App.js: import 'typeface- ...

Embed a javascript tag to print a PDF document

I have been struggling with printing a PDF file using JavaScript. I attempted to use the embed trick suggested in this Silent print a embedded PDF but unfortunately, the print function remained undefined. Then, I tried another approach using an Iframe and ...