Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace nonNumeric 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?

like image 487
PsyGnosis Avatar asked May 23 '11 12:05

PsyGnosis


People also ask

How do I remove numbers from a string in JavaScript?

To remove all numbers from a string, call the replace() method, passing it a regular expression that matches all numbers as the first parameter and an empty string as the second. The replace method will return a new string that doesn't contain any numbers.

How do I remove a character from a number string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

Can we use \n in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


2 Answers

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,"");
like image 114
DavidJCobb Avatar answered Sep 27 '22 21:09

DavidJCobb


var input = document.getElementById('phone');
input.onkeypress = function(){
    input.value = input.value.replace(/[^0-9+]/g, '');
}
like image 24
bjornd Avatar answered Sep 27 '22 20:09

bjornd