PsyGnosis
PsyGnosis

Reputation: 1499

Replace non-numeric characters with JavaScript?

I use the regular expression /^\+(90)[2-5]{1}[0-9]{9}$/ for phone validation, but when someone enters any special characters (such as * - / ( ) - _) in the input, I want to replace the characters with an empty string (remove them). Note that I don't want to replace the +.

How can I do that?

Upvotes: 16

Views: 23293

Answers (2)

bjornd
bjornd

Reputation: 22943

var input = document.getElementById('phone');
input.onkeypress = function(){
    input.value = input.value.replace(/[^0-9+]/g, '');
}

Upvotes: 2

DavidJCobb
DavidJCobb

Reputation: 1131

This will remove all non-numeric characters in a given string:

myString = myString.replace(/\D/g,"");

\D matches anything that isn't a number; \d matches a number.


Misread the question. To remove all non-numeric characters except +, do:

myString = myString.replace(/[^\d\+]/g,"");

Upvotes: 41

Related Questions