JavaScript,如何检查字符是否为以下任何一种



例如 var currentWord = "hello.";

如何检查当前单词是否以"." "," "!" "?" ";" ":"结尾?

我必须有一堆 if else 语句吗?这是我现在拥有的代码,可以工作,但实际上是多余的

if (
  currentWord.slice(-1) == "." || 
  currentWord.slice(-1) == "," || 
  currentWord.slice(-1) == "!" || 
  currentWord.slice(-1) == "?" || 
  currentWord.slice(-1) == "?" || 
  currentWord.slice(-1) == ";" || 
  currentWord.slice(-1) == ":"
) {

像这样使用正则表达式。如果您不想使用它,则不需要使用它。

if (currentWord.match(/[.,!?;:]$/)) {
alert("matched");
}

不过这仍然有效...

if (currentWord.slice(-1).match(/[.,!?;"]/)) {
alert("matched");
}

您可以创建一个字符数组,然后使用 .indexOf() 方法。在这种情况下,您可以简单地使用 chars.indexOf(currentWord.slice(-1)) > -1 其中chars是由字符组成的数组。

var currentWord = "hello.",
    chars = [".", ",", "!", "?", ";", ":"],
    endsInChar = chars.indexOf(currentWord.slice(-1)) > -1;
console.log(endsInChar); // true

或者,您可以将基本正则表达式与 .test() 方法一起使用。

在这种情况下,您可以使用/[.,!?;:]$/.test(currentWord)其中[.,!?;:]是字符的字符集,$是断言字符串末尾的锚点。

var currentWord = "hello.",
    endsInChar = /[.,!?;:]$/.test(currentWord);
console.log(endsInChar); // true

虽然可以使用正则表达式来完成,但我更喜欢数组

// warning, typed on the fly, untested
var punc = ['.', '?'];
var lastChar = currentWord.slice(-1);
if (punc.indexOf(lastChar) >= 0) {
   // Ended with a punctuation symbol
} else {
   // Otherwise
}

许多人更喜欢数组选项,但是,正则表达式是一个非常有用的工具,您也可以使用它们。

例如:

var word = prompt("Word?")
alert(/[.,!?;:]$/.test(word))

反斜杠的原因是:

  • 正则表达式中的.意味着任何字符,我们想要一个字面. .
  • ?正则表达式中的标记使前面的令牌可选,天知道这在[]中做了什么。

因此,我逃脱了那些角色。

相关内容

最新更新