Check if String contains only Letters and Numbers in JS-Code Examples

Radu TM

Check if String contains only Letters and Numbers in JS

JavaScript by Radu TM June 22, 2022

// This function will check if a string contains only letters and numbers.

function checkString(str) {
  // Use a regular expression to remove all non-letter and non-number characters.
  str = str.replace(/[^A-Za-z0-9]/g, '');

  // If the string is empty after removing all non-letter and non-number
  // characters, then it contains only letters and numbers.
  if (str.length === 0) {
    return true;
  }

  // Otherwise, the string contains at least one character that is not a letter
  // or number.
  return false;
}

// Test the checkString function.

console.log(checkString('abc123')); // true
console.log(checkString('[email protected]#')); // false
console.log(checkString('123')); // true
console.log(checkString('')); // true
console.log(checkString('[email protected]#')); // false

0

28.172

Check if String contains only Letters and Numbers in JS

JavaScript by Radu TM June 22, 2022

var str = "Hello, world!";

// Check if string contains only letters and numbers
var regex = /^[a-z0-9]+$/i;
if (regex.test(str)) {
  console.log("String contains only letters and numbers");
} else {
  console.log("String contains other characters");
}

0

28.172

Check if String contains only Letters and Numbers in JS

JavaScript by Radu TM June 22, 2022

const string = "I ❤️ JS";

// Checks if the string contains only letters and numbers.
const result = /^[a-zA-Z0-9]+$/.test(string);

console.log(result); // false

0

28.172

Check if String contains only Letters and Spaces in JS

JavaScript by Radu TM June 22, 2022

function isStringOnlyLettersAndSpaces(str) {
  // We use a Regular Expression to check if the string only contains letters and spaces
  // The "i" at the end of the expression makes it case insensitive
  var regex = /^[a-z\s]+$/i;

  // We return true if the string passes the regex test
  return regex.test(str);
}

// Test the function
console.log(isStringOnlyLettersAndSpaces("I love JS")); // true
console.log(isStringOnlyLettersAndSpaces("I #JS")); // false

0

11.985

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories