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?
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.
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.
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.
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,"");
var input = document.getElementById('phone');
input.onkeypress = function(){
input.value = input.value.replace(/[^0-9+]/g, '');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With