TheDetailer
TheDetailer

Reputation: 299

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;
}

Upvotes: 0

Views: 67

Answers (3)

leroyJr
leroyJr

Reputation: 1160

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
}

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36438

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

Upvotes: 2

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21565

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 $.

Upvotes: 0

Related Questions