2

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?

xec
  • 17,349
  • 3
  • 46
  • 54
Dom
  • 3,126
  • 14
  • 46
  • 68
  • try this... http://stackoverflow.com/questions/181356/regex-to-match-alphanumeric-and-spaces – asharajay Sep 25 '13 at 08:37
  • where do you want to add space exactly? – Mehmed Sep 25 '13 at 08:38
  • possible duplicate of [How to allow only numeric (0-9) in HTML inputbox using jQuery?](http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery) – Ram Sep 25 '13 at 08:38

3 Answers3

7

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.

Community
  • 1
  • 1
xec
  • 17,349
  • 3
  • 46
  • 54
  • Your link works fine if the user types the text but it fails if the user pastes the text. – schlingel Sep 25 '13 at 09:15
  • 1
    @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: http://jsfiddle.net/7rSVb/3/ – xec Sep 25 '13 at 09:56
3

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

schlingel
  • 8,560
  • 7
  • 34
  • 62
  • 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? – Dom Sep 25 '13 at 08:46
0

use \s - Matches a single white space character, including space, tab, form feed, line feed. Equivalent to

Regex Guide

Anand
  • 14,545
  • 8
  • 32
  • 44