Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: check if a giving string contains only letters or digits [duplicate]

Tags:

javascript

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 :)

like image 763
senior Avatar asked Sep 08 '14 14:09

senior


People also ask

How do you check if a string contains only letters and numbers in JavaScript?

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!

How do you check if a string only contains letters in JS?

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.

Which method returns true if a string consists of only letters and numbers and is not blank?

The isalnum() method returns True if all characters in the string are alphanumeric (either alphabets or numbers). If not, it returns False.

How do I check if a string contains letters?

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.


1 Answers

Add 0-9 also to your regex

 boolean onlyLetters(String str) {
   return str.match("^[A-Za-z0-9]+$");
 }
like image 146
bugwheels94 Avatar answered Oct 04 '22 01:10

bugwheels94