Check if String contains Special Characters in JavaScript-Code Examples

Radu TM

Check if String contains Special Characters in JavaScript

JavaScript by Radu TM • June 22, 2022

// check if string contains special characters
const checkSpecialCharacters = (str) => {
  // create regex to check for special characters
  const regex = /[^a-zA-Z0-9 ]/g;
  // if there are any special characters, return true
  if (regex.test(str)) {
    return true;
  }
  // otherwise return false
  return false;
};

// check if "Hello! 😃" contains any special characters
console.log(checkSpecialCharacters("Hello! 😃")); // true

0

24.867

Check if String contains Special Characters in JavaScript

JavaScript by Radu TM • June 22, 2022

const hasSpecialCharacters = (str) => {
  // Use a regular expression to check for special characters
  return /[^a-zA-Z0-9]/.test(str);
};

// Test the function
console.log(hasSpecialCharacters('abcdefg')); // false
console.log(hasSpecialCharacters('abcdefg!')); // true
console.log(hasSpecialCharacters('abcdefg💩')); // true

0

24.867

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories