skip to Main Content

I want to check if a single character is special in regex.

let char = "?";
if(condition){
  console.log("The char is a special character");
}

3

Answers


  1. const format = /[!@#$%^&*()_+-=[]{};':"\|,.<>/?]+/;
    
    const checkFormat = (string) => {
        if(format.test(string)){
          return console.log("The char is a special character");
        } else {
          return console.log("No special character");
        }
    }
    checkFormat('?');
    Login or Signup to reply.
  2. let char = "?";
    let condition = /[^a-zA-Z1-4]/g;
    
    if (condition.test(char)) {
        console.log("The char is a special character");
    }
    
    Login or Signup to reply.
  3. in a RegExp W represents each special character

    definition : W Matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_].

    You can find a list of those characters here :

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes

    const format = /W/g;
    
    const checkFormat = (string) => {
        if(format.test(string)){
          return (`The char "${string}" is a special character`);
        } else {
          return (`The char "${string}" is not a special character`);
        }
    }
    alert(checkFormat("?"));
    alert(checkFormat("n"));
    alert(checkFormat("☺️"));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search