Check if String contains only Spaces in JavaScript-Code Examples

Radu TM

Check if String contains only Spaces in JavaScript

JavaScript by Radu TM ā€¢ June 22, 2022

const checkSpaces = str => {
  // We use a Regular Expression to check if the string only contains spaces.
  return /^\s+$/.test(str);
};

console.log(checkSpaces("")); // true
console.log(checkSpaces(" ")); // true
console.log(checkSpaces("  ")); // true
console.log(checkSpaces("   ")); // true
console.log(checkSpaces("\t\t")); // true
console.log(checkSpaces("\n\n")); // true

console.log(checkSpaces("a")); // false
console.log(checkSpaces(" a")); // false
console.log(checkSpaces("a ")); // false
console.log(checkSpaces("a  ")); // false
console.log(checkSpaces(" a ")); // false
console.log(checkSpaces("  a")); // false
console.log(checkSpaces("\t a\t ")); // false
console.log(checkSpaces("\n a\n ")); // false

console.log(checkSpaces("šŸ™„")); // false
console.log(checkSpaces("  šŸ™„ ")); // false
console.log(checkSpaces("\tšŸ™„\t")); // false
console.log(checkSpaces("\nšŸ™„\n")); // false

0

23.447

Check if String contains only Spaces in JavaScript

JavaScript by Radu TM ā€¢ June 22, 2022

let str = "   ";

// check if string only contains spaces
if (str.trim().length === 0) {
  console.log("string only contains spaces");
} else {
  console.log("string contains other characters");
}

0

23.447

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

10.662

Check if String contains only Letters and Spaces in JS

JavaScript by Radu TM ā€¢ June 22, 2022

function checkString(str) {
  let regex = /^[a-zA-Z\s]+$/; // create regular expression to check for letters and spaces
  return regex.test(str); // test the string against the regular expression
}

// test the function
console.log(checkString("Hello world!")); // true
console.log(checkString("Hello world!šŸŒŽ")); // false

0

10.662

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories