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?
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?
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.
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
use \s
- Matches a single white space character, including space, tab, form feed, line feed. Equivalent to