Regex to remove letters, symbols except numbers

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.

143883 次浏览

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.

Simple:

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

^ - means NOT

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.

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

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

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.