Replacing alpha characters and spaces in string with jQuery
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
Related videos on Youtube
Dom
Updated on June 04, 2022Comments
-
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?
-
asharajay over 10 yearstry this... stackoverflow.com/questions/181356/…
-
Mehmed over 10 yearswhere do you want to add space exactly?
-
Ram over 10 yearspossible duplicate of How to allow only numeric (0-9) in HTML inputbox using jQuery?
-
-
Dom over 10 yearsThat'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 over 10 yearsYour link works fine if the user types the text but it fails if the user pastes the text.
-
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