How do you check if a string contains only alphabets and numbers in 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 :)

asked Sep 8, 2014 at 14:09

seniorsenior

2,1166 gold badges36 silver badges54 bronze badges

0

Add 0-9 also to your regex

 boolean onlyLetters(String str) {
   return str.match("^[A-Za-z0-9]+$");
 }

answered Sep 8, 2014 at 14:10

bugwheels94bugwheels94

29.2k3 gold badges37 silver badges59 bronze badges

3

Using regexp, you can add 0-9 to say any digit between 0 and 9:

boolean onlyLettersAndDigits(String str) {
      return str.matches("^[a-zA-Z0-9]+$");
    }

answered Sep 8, 2014 at 14:11

1

Not the answer you're looking for? Browse other questions tagged javascript or ask your own question.

How do you check if a string contains only alphabets and numbers in javascript?

1. The RegExp test() Method

To check if a string contains only letters and numbers in JavaScript, call the test() method on this regex: /^[A-Za-z0-9]*$/. If the string contains only letters and numbers, this method returns true. Otherwise, it returns false.

function onlyLettersAndNumbers(str) {
return /^[A-Za-z0-9]*$/.test(str);
}
const str1 = 'number60';
const str2 = 'contains spaces';
const str3 = 'has special characters !@#$%^&';
console.log(onlyLettersAndNumbers(str1)); // true
console.log(onlyLettersAndNumbers(str2)); // false
console.log(onlyLettersAndNumbers(str3)); // false

The RegExptest() method searches for a match between the regular expression and a specified string.

The / and / characters are used to start and end the regular expression.

The ^ character matches the beginning of the string, while the $ character matches the end of the string.

The square brackets ([]) are used to match any one of multiple specified patterns. In our example, we specify three patterns: A-Z, a-z, and 0-9.

A-Z matches any uppercase letter.

a-z matches any lowercase letter.

0-9 matches any digit.

The * character matches zero or more occurrences of a particular pattern. We add it after the square brackets to match any of the patterns in the brackets as many times as possible.

2. The String match() Method

We can use the String match() method in place of RegExp test().

function onlyLettersAndNumbers(str) {
return Boolean(str.match(/^[A-Za-z0-9]*$/));
}
const str1 = 'number60';
const str2 = 'contains spaces';
const str3 = 'has special characters !@#$%^&';
console.log(onlyLettersAndNumbers(str1)); // true
console.log(onlyLettersAndNumbers(str2)); // false
console.log(onlyLettersAndNumbers(str3)); // false

The String match() method returns an array of all the matches of a regular expression in a string. If there are no matches, it returns null.

const str1 = 'number60';
const str2 = 'contains spaces';
const str3 = 'has special characters !@#$%^&';
// [ 'number60', index: 0, input: 'number60', groups: undefined ]
console.log(str1.match(/^[A-Za-z0-9]*$/));
console.log(str2.match(/^[A-Za-z0-9]*$/)); // null
console.log(str3.match(/^[A-Za-z0-9]*$/)); // null

We pass the result of match() to the Boolean constructor to convert it to a Boolean. Boolean() converts truthy values to true, and falsy values to false.

In JavaScript, there are six falsy values: undefined, null, NaN, 0, '' (empty string), and false. Every other value is truthy.

console.log(Boolean(undefined)); // false
console.log(Boolean(['number60'])); // true
console.log(Boolean(null)); // false
console.log(Boolean(5)); // true

Removing Letters and Numbers from a String

If you would like to remove any letters and numbers from the string, you can use the String replace() method.

function removeLettersAndNumbers(str) {
return str.replace(/[A-Za-z0-9]/g, '');
}
const str1 = 'number!60 ?';
const str2 = '#wel_com%e';
console.log(removeLettersAndNumbers(str1)); // ! ?
console.log(removeLettersAndNumbers(str2)); // #_%

The String replace() method returns a new string with some or all matches of a specified pattern replaced by a replacement. We use an empty string ('') as the replacement to have all the letters and numbers removed in the resulting string.

We use the g (global) flag to match all the occurrences of the pattern in the string. If we don't specify this flag, only the first match of a letter or number will be removed.

function removeLettersAndNumbers(str) {
// 'g' flag not set
return str.replace(/[A-Za-z0-9]/, '');
}
const str1 = 'number!60 ?';
const str2 = '#wel_com%e';
console.log(removeLettersAndNumbers(str1)); // umber!60 ?
console.log(removeLettersAndNumbers(str2)); // #el_com%e

Updated at: codingbeautydev.com

Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

How do you check if a string contains only alphabets and numbers in javascript?

Sign up and receive a free copy immediately.

How do I check if a string contains letters and numbers?

To check whether a String contains only unicode letters or digits in Java, we use the isLetterOrDigit() method and charAt() method with decision-making statements. The isLetterOrDigit(char ch) method determines whether the specific character (Unicode ch) is either a letter or a digit.

How do you check if a string only contains alphabets in JavaScript?

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. Copied!

How do you check if a string is only alphabets?

We can use the regex ^[a-zA-Z]*$ to check a string for alphabets. This can be done using the matches() method of the String class, which tells whether the string matches the given regex.

How do I check if a string contains only characters?

Java For Testers Read the String. Convert all the characters in the given String to lower case using the toLower() method. Convert it into a character array using the toCharArray() method of the String class. Find whether every character in the array is in between a and z, if not, return false.