Regex to remove letters, symbols except numbers
130,616
Solution 1
You can use \D
which means non digits.
var removedText = self.val().replace(/\D+/g, '');
You could also use the HTML5 number input.
<input type="number" name="digit" />
Solution 2
Use /[^0-9.,]+/
if you want floats.
Solution 3
Simple:
var removedText = self.val().replace(/[^0-9]+/, '');
^ - means NOT
Solution 4
Try the following regex:
var removedText = self.val().replace(/[^0-9]/, '');
This will match every character that is not (^
) in the interval 0-9.
Demo.
Solution 5
If you want to keep only numbers then use /[^0-9]+/
instead of /[^a-zA-Z]+/
Comments
-
MacMac almost 2 years
How can you remove letters, symbols such as
∞§¶•ªºº«≥≤÷
but leaving plain numbers 0-9, I want to be able to not allow letters or certain symbols in an input field but to leave numbers only.Demo.
If you put any symbols like
¡ € # ¢ ∞ § ¶ • ª
or else, it still does not remove it from the input field. How do you remove symbols too? The\w
modifier does not work either.-
user3167101 almost 13 years
\w
is not a modifier but a shortcut of[A-Za-z0-9_]
or word characters.
-
-
bezmax almost 13 yearsI hate being 32 seconds late :D
-
Darin Dimitrov almost 13 years@Max, no problem. Despite this you were the one that got upvoted first :-)
-
Doug Harris over 12 yearsProbably want to replace more than just the first non-digit found -- change regexp to
/\D+/
-
gnysek about 10 yearsshouldn't it be
/\D+/g
? -
cassi.lup about 10 years
/\D+/g
has the same effect as to/\D/g
. -
user3167101 about 9 yearsIf you want a string that could contain a float value ;)
-
Pere about 9 yearsI find the fiddle for number input unuseful: a) it includes the javascript for removing non-numbers and b) if the above js is removed, it does nothing (for me) for the purpose of removing non-numbers
-
user3167101 about 9 years@Pere You still need to validate it yourself. It does give you the arrows for incrementing/decrementing the number though.
-
Joeri over 7 yearsvar removedText = self.val().replace(/[^0-9]+/g, ''); to keep all numbers. albeit 8.10+3 would give 8103... Not sure that is what's asked for in the question.
-
tourist about 6 yearswhat is that "," for?
-
Klemen Tusar almost 6 years@sbk in some regions they use the comma instead of the dot to mark decimal places :)
-
Hernán Eche about 5 yearsalso negatives /[^-0-9.,]+/
-
Vasiliy Zverev over 3 years.keydown() is not enough if user is allowed to paste text into field.
-
letie about 3 years@KlemenTusar I tried this one with "245k" and didn't work..