【问题标题】:check if a string only has punctuation in it in javascript在javascript中检查字符串是否只有标点符号
【发布时间】:2015-04-13 10:53:32
【问题描述】:

在 if 语句中,我想检查字符串中是否有标点符号。如果它有标点符号,我想弹出一条警告消息。

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

我是否需要正则表达式,或者是否有自动方法可以为我执行此操作? 提前致谢!

【问题讨论】:

标签: javascript if-statement punctuation


【解决方案1】:

您不需要 正则表达式,但这可能是最简单的。这是一个直截了当的字符类,将您要禁止的字符放入[...],例如:

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

请注意,在[] 中,- 是特殊的,因此如果要包含它,请在其前面加上反斜杠(如上)。与反斜杠相同,来吧。


请注意,您永远不需要在条件中写入== true。如果你愿意,你可以,但从 JavaScript 引擎的角度来看,它没有任何作用。

【讨论】:

  • [] 或 {} 或 () 怎么样?它们也很特别吗?
  • @StephenGevanni:最简单的事情就是检查一些文档。 The spec 很难阅读,但 MDN's page 非常好。列表中只有一个字符在字符类中是特殊的:](因为它结束了类)。其他都不是。不过,其他字符类之外是特殊的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-17
  • 1970-01-01
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多