简体   繁体   中英

Writing a regex expression for special characters in JavaScript

I know my code is wrong, I am trying to test for certain characters, and as long as they exist for each char in the input field, it will pass true, otherwise pass false.

function isChar(value) {
    //Trying to create a regex that allows only Letters, Numbers, and the following special characters    @ . - ( ) # _   

    if (!value.toString().match(/@.-()#_$/)) {              
        return false;
    } return true;
}

Assuming you're actually passing a character (you don't show how this is called), this should work:

 function isChar(value) { if (!value.toString().match(/[a-z0-9@.\\-()#_\\$]/i)) { return false; } else return true; } console.log(isChar('%')); // false console.log(isChar('$')); // true console.log(isChar('a')); // true 

If instead you're passing a string, and wanting to know if all the characters in the string are in this "special" list, you'll want this:

 function isChar(value) { if (! value.match(/^[a-z0-9@.\\-()#_\\$]*$/i)) { return false; } else return true; } console.log(isChar("%$_")); // false console.log(isChar("a$_")); // true 

Characters that have meaning in regexp need to be escaped with \\ . So for example you would replace $ with \\$ and so on for the other such characters. So the final regexp would look like:

@.\-()#_\$

Since you need to escape both the - and the $ .

The \\w class will catch the alpha numeric. The rest you provided (but properly escaped):

function isChar(value) {
  return value.toString().match(/[\w@.\-()#_\$]/) ? true : false
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM