Using JavaScript, I wanna check if a giving string contains only letters or digits and not a special characters:
I find this code which checks if a string contains only letters:
boolean onlyLetters(String str) {
return str.match("^[a-zA-Z]+$");
}
but my string can contain digits too. can you help me?
thanks in advance :)
Use the test() method on the following regular expression to check if a string contains only letters and numbers - /^[A-Za-z0-9]*$/ . The test method will return true if the regular expression is matched in the string and false otherwise. Copied!
Use the test() method to check if a string contains only letters, e.g. /^[a-zA-Z]+$/. test(str) . The test method will return true if the string contains only letters and false otherwise.
The isalnum() method returns True if all characters in the string are alphanumeric (either alphabets or numbers). If not, it returns False.
To check if a string contains any letters, use the test() method with the following regular expression /[a-zA-Z]/ . The test method will return true if the string contains at least one letter and false otherwise.
Add 0-9 also to your regex
boolean onlyLetters(String str) {
return str.match("^[A-Za-z0-9]+$");
}
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