Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all commas in a string with JQuery/Javascript

I have a form where I have a couple hundred text boxes and I'd like to remove any commas when they are loaded and prevent commas from being entered. Shouldn't the follow code work assuming the selector is correct?

$(document).ready(function () {
  $("input[id*=_tb]")
  .each(function () {
      this.value.replace(",", "")
  })
  .onkeyup(function () {
      this.value.replace(",", "") 
  })
});
like image 533
duckmike Avatar asked Aug 21 '12 12:08

duckmike


People also ask

How to replace all commas in a string in jquery?

Use the replaceAll() method to replace all commas in a string, e.g. str. replaceAll(',', ' ') . The replaceAll method takes a substring and a replacement as parameter and returns a new string with all matches replaced by the provided replacement.

How do I remove all commas from a string?

To remove all commas from a string, call the replace() method, passing it a regular expression to match all commas as the first parameter and an empty string as the second parameter. The replace method will return a new string with all of the commas removed.

How do you replace all occurrences of a character in a string in JavaScript?

To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')

How do you replace commas with new lines?

Select the cells containing the commas you need to replace with newlines, then press the Alt + F11 keys simultaneously to open the Microsoft Visual Basic for Applications window. 3. Press the F5 key or click the Run button to run the code. Then all commas in selected cells are replaced with newlines immediately.


2 Answers

$(function(){
    $("input[id*=_tb]").each(function(){
        this.value=this.value.replace(/,/g, "");
    }).on('keyup', function(){
        this.value=this.value.replace(/,/g, "");
    });
});

See here for an explanation and examples of the javascript string.replace() function:

http://davidwalsh.name/javascript-replace

as @Vega said, this doesn't write the new value back to the textbox - I updated the code to do so.

like image 174
totallyNotLizards Avatar answered Oct 07 '22 18:10

totallyNotLizards


Use a regex with the g flag instead of a string: .replace(/,/g, "").

like image 30
sp00m Avatar answered Oct 07 '22 18:10

sp00m