85

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.

MacMac
  • 34,294
  • 55
  • 151
  • 222

6 Answers6

143

You can use \D which means non digits.

var removedText = self.val().replace(/\D+/g, '');

jsFiddle.

You could also use the HTML5 number input.

<input type="number" name="digit" />

jsFiddle.

alex
  • 479,566
  • 201
  • 878
  • 984
43

Use /[^0-9.,]+/ if you want floats.

Klemen Tusar
  • 9,261
  • 4
  • 31
  • 28
22

Simple:

var removedText = self.val().replace(/[^0-9]+/, '');

^ - means NOT

bezmax
  • 25,562
  • 10
  • 53
  • 84
  • var 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. – Joeri Feb 05 '17 at 10:24
7

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
4

If you want to keep only numbers then use /[^0-9]+/ instead of /[^a-zA-Z]+/

Aziz Shaikh
  • 16,245
  • 11
  • 62
  • 79
0

Excluding special characters:

/^[^@~!@#$%^&()_=+\';:"/?>.<,-]$/`

This regular expression helps to exclude special characters from the input.

Exclude special characters and emojis:

/^([^\u2700-\u27BF\uE000-\uF8FF\uDD10-\uDDFF\u2011-\u26FF\uDC00-\uDFFF\uDC00-\uDFFF\u005D\u007C@~!@#$%^&()_=+[{}"\';:"/?>.<,-\s])$/`

This is a regular expression to exclude both special characters and emojis from the input. Given are the Unicode ranges of the emojis, mathematical symbols, and symbols in other languages.

nima
  • 7,796
  • 12
  • 36
  • 53