16

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?

1
  • can you provide and example of what you want to do? Commented May 23, 2011 at 12:53

2 Answers 2

42

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,"");
Sign up to request clarification or add additional context in comments.

4 Comments

but I want only plus ( +) you know my phone number starts with +90
@psygnosis: Sorry, I misread your question. Just edited this answer with a solution that will keep + signs.
No need to escape + inside a character group.
thank you it worked if I use the same code line..with username only alphabet characters myString.replace(/\W/g,"") is this work?
2
var input = document.getElementById('phone');
input.onkeypress = function(){
    input.value = input.value.replace(/[^0-9+]/g, '');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.