Properly showcasing commas

Need help adding commas to numbers. Currently, my output is 1,2,3,4,5,6,7,890 but I want it to be 1,234,567,890. I am using keyup which is causing some problems. Any suggestions?

numberWithCommas : function () {
  var target = $("#foo");
  target.val(target.val().toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
},

Update: I have discovered that

replace(/\B(?=(\d{3})+(?!\d))/g, ',');
solved the issue of excessive commas.

Answer №1

Get rid of all existing commas and then add new ones in the correct positions:

addCommasToNumber : function () {
  $("#foo").val(function(_,val) {
    return val.replace(/\,/g,'').replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  });
},

Check out this FIDDLE

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

Error message: The recursive function is unable to return a value when operating

My current task involves solving this problem recursively: Clean the room function: given an input of [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20], create a function that organizes these into individual arrays that are ordered. For example, answer(ArrayFromAb ...

Breakpoints in VS Code unexpectedly shift to different lines

While I am still working on resolving my other issue related to randomly failing tests using jest and supertest in Node.js, I decided to utilize the VS Code debugger. Initially, I expected it to be straightforward but encountered an unexpected behavior whe ...

Tips on preserving a dynamic web page within a Cordova application

I have developed a project and To Do list App that operates on a single HTML page with just an "add To Do list" button. Users can click on this button to create a To Do list and add tasks within it, all of which are dynamically generated as HTML elements. ...

What is the best way to implement debounce in an asynchronous function?

Is it possible to implement the debounce function with an async method? I have a specific scenario in my vue-app where I am making continuous API calls within a method and I would like to prevent this. This is the method in question: methods: { async ...

Deleting multiple data records in PHP/SQL by using a Select Option

Currently, I have developed a system that allows for the deletion of multiple data using a select option. However, I am facing some issues with this functionality. When only one data is selected and the delete button is pressed, it successfully deletes the ...

The functionality of bigvideo.js is not supported on the Opera browser

I am facing an issue with the bigvideo.js script as it does not seem to be working on the Opera browser. Do you have any suggestions for a solution? I successfully used this script in Firefox. $(function() { var BV = new $.BigVideo({useFlashForFirefo ...

BS Modal was improperly invoked, leading to an illegal instantiation

Currently, I am attempting to trigger a bootstrap Modal in Angular by utilizing the component instead of its HTML attribute. However, I am encountering an error (specifically, illegal invocation). Here is the code snippet from the component: @ViewChild(&a ...

React: The art of organizing components. Exploring Composition and Render props

Are you prepared for this long question? I've recently delved into working with react-query and noticed that a significant amount of code needs to be duplicated for each component utilizing the useQuery hook. For instance: if(query.isLoading) { re ...

Tips for saving images in an S3 bucket

Within my express application, I currently save images to a directory in my repository. However, I am beginning to think that this approach may not be ideal and I am considering using AWS S3 as an alternative storage solution. Since I have never worked w ...

Creating an iterable type in TypeScript with key-value pairs - a beginner's guide

I am trying to define a type in TypeScript that represents an object with dynamically generated keys. How can I achieve this? { dog: true, cat: true, x: true } Currently, I am using the 'any' type but I would like to define a proper t ...

Update the DOM elements following the completion of an AJAX load operation

Let me explain the issue I'm encountering: I begin with <container> <div id="foo"></div> </container> After that, I populate content into the container div using Ajax <container> <div id="bar"></div&g ...

Tips for transferring the data from one yform value to another field

Within our online store, some products feature a yForm to consolidate various parts of the product. Is there a straightforward method to automatically transfer the sum field value to another field, such as the product quantity (which does not use yForm)? I ...

Using MEAN.JS to Define Query Parameters for Mongo from the Client Controller

I am currently developing an application using the MEAN stack - MongoDB, Angular, Express, and Node.js. To kickstart my project, I utilized the MEAN.JS generator to set up the initial structure of my application. The articles module within my application ...

How to Resolve jQuery Script Delay Caused by AJAX Request?

I am in the process of creating a unique responsive Wordpress Theme, with only one page that loads content via AJAX. Here is the AJAX function I have implemented: jQuery(document).ready(function(){ jQuery.ajaxSetup({cache:false}); jQuery(" ...

Save property using the useState hook

I am working on implementing a sorting function in the child component, where the props are passed in from the parent through an axios call. Should I: Store the prop in the child component's useState? Pass the parent's setState function as a pro ...

What causes the unexpected behavior of str.replace() when the replacement string contains a regex pattern?

let a = `<script crossOrigin="anonymous" src="//example.com/index.js"></script>` let regex = new RegExp( `<script(.*?) src="` + '//example.com/index.js' + `"></script>`, 'g') let replacementString = ...

Fluctuating Values in Array Distribution

I have a set of users and products that I need to distribute, for example: The number of values in the array can vary each time - it could be one value one time and three values another time. It is important that each user receives a unique product with ...

How can I send styles to a child component and utilize them as scoped styles within Vue?

One of my components is a parent: <template> <ChildComponent :styles="styles" /> </template> <script> export default { data: () => ({ styles: ` p { color: red } ` ...

Using AngularJs, you can access the document.body.onfocus event within the controller of

I am attempting to detect when the user closes or cancels the File Upload Window <input type="file"> Since there isn't a built-in listener for the close event of the file upload, I am trying to capture it using the document.body.focus event, s ...

Is the latest Swiper JS version compatible with outdated web browsers?

Seeking information on browser compatibility. I am interested in upgrading to the latest version 8.4.5 of Swiper JS for my project, currently using version 4.1.6. Upon examining their shared Github repository file .browserslistrc, I noticed changes that ta ...