1

In an if statement, I want to check if the string has punctuation in it. If it has punctuation, I want an alert message to pop up.

if((/*regex presumably*/.test(rspace))==true||(/*regex presumably*/.test(sspace))==true){
    alert('Please enter your guessed answer in the fields provided, without punctuation marks.');

    //if only punctuation are entered by the user, an alert message tells them to enter something.
}

Do I need a regex, or is there an automatic method to do this for me? Thanks in advance!

Stephen Gevanni
  • 43
  • 1
  • 11

1 Answers1

3

You don't need regex, but that would probably be simplest. It's a straight forward character class, put the characters you want to disallow inside [...], e.g.:

if (/[,.?\-]/.test(rspace)) {
    // ....
}

Note that within [], - is special, so if you want to include it put a backslash before it (as above). Same with backslash, come to that.


Note that you never need to write == true in a condition. You can if you want, but it serves no purpose from the JavaScript engine's perspective.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • what about [] or {} or ()? Are they special too? – Stephen Gevanni Apr 13 '15 at 11:02
  • 1
    @StephenGevanni: Easiest thing to do is to check some documentation. [The spec](http://ecma-international.org/ecma-262/5.1/#sec-7.8.5) is pretty hard to read, but [MDN's page](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions) is pretty good. Only one of the characters in your list is special inside a character class: `]` (as it ends the class). None of the others are. The others are special *outside* a character class, though. – T.J. Crowder Apr 13 '15 at 11:23