Replacing alpha characters and spaces in string with jQuery

10,159

Solution 1

To match only non-numerics, you would do [^0-9] instead of [a-zA-Z] (this is called a negated character class).

If you want an input to allow only numbers, with HTML5 you can simply do <input type="number">. For wider support, there are plenty of JavaScript solutions, have a look at How to allow only numeric (0-9) in HTML inputbox using jQuery? as suggested in the comments.

Solution 2

Just add the space to your Regex:

  "asfasd asdf asdf".replace(/([a-zA-Z ])/g, "");

Yields:

  ""

Edit: I misunderstood your question. If you want to prevent every input but numbers use this regex:

function removeNotAllowedChars($input) {
   $input.val($input.val().replace(/[^0-9]/g, ''));
}

$('#myText')
   .keyup(function() {
     var $input = $(this);
     removeNotAllowedChars($input);
   })
   .change(function() {
     var $input = $(this);
     removeNotAllowedChars($input);
   });

Using these script removes the input instantly if the user types the character and if he pastes the input after the focus changes. Try it here: JSFiddle

Share:
10,159

Related videos on Youtube

Dom
Author by

Dom

Updated on June 04, 2022

Comments

  • Dom
    Dom almost 2 years

    I have a string that allows only numbers

    $(this).val($(this).val().replace(/([a-zA-Z])/g, ""));
    

    How can I add a space, so this will get replaced with "" same way in one string?

  • Dom
    Dom over 10 years
    That's great, thank you, but just thinking that would be easier to prevent the space key in general. This is my function $('*[data-type-validation="numeric"]).each(function (index, value) { $(this).change(function () { $(this).val($(this).val().replace(/([a-zA-Z ])/g, "")); }) }); any idea please?
  • schlingel
    schlingel over 10 years
    Your link works fine if the user types the text but it fails if the user pastes the text.
  • xec
    xec over 10 years
    @schlingel There are plenty of different solutions at that link, but it does indeed seem like they are all using different key-events instead of the input event. I edited your fiddle: jsfiddle.net/7rSVb/3