0

I'm trying to create a regular expression to detect if the string has a special character.

/[!$&*-\=^`|~#%'+?{}._]+/.test('Hello2016'); // returns true when should return false because there's no special character

In the previous sample, it's returning true. I guess it's related to the = symbol but I don't know where it's the mistake.

oscar.fimbres
  • 1,145
  • 1
  • 13
  • 24
  • 1
    What is a special character? Anything not a-Z 0-9? then sheeldotme already answered your question. If you are using user input and want to use that as a regular expression then the aldanux comment would help or you could look how google does it: https://github.com/google/closure-library/blob/master/closure/goog/string/string.js#L1134 – HMR May 13 '16 at 02:02

3 Answers3

3

It's actually because of the - character. Inside of a character class ([...]) it represents a range of characters. For example [a-f] would match a, b, c, d, e, or f.

The correct pattern would be:

/[!$&*\-=^`|~#%'+?{}._]+/

You haven't actually specified what you consider a 'special character', but a far simpler pattern would be:

/[^\W_]/

This will match an underscore or any character that's not a Latin letter or decimal digit (\W).

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
0

If you'd like to detect all special characters, validate that the string includes only the characters you want, that way special characters you did not account for get flagged as special characters. This makes your code applicable in more scenarios and makes it future proof.

if(!name.match(/^[a-zA-Z0-9]+$/i)) {
    // handle the case where there are special characters in the string
}
sheeldotme
  • 2,237
  • 14
  • 27
0

You shoud escape regular expression's special charactors like this.

[!\$&\*\-\\=^`|~#%'\+\?{}\._]

These have special meaning in regular expression.

$*-\+?.

And maybe this also works.

!/^[A-Za-z0-9]+$/.test('Hello2016')
Pontarlier
  • 21
  • 5