var currentWord = "hello.";
如何检查currentWord是否以"." "," "!" "?" ";" ":"
结尾?
我是否必须拥有一堆if else语句? 这是我现在的代码,它可以工作,但实际上是多余的
if (
currentWord.slice(-1) == "." ||
currentWord.slice(-1) == "," ||
currentWord.slice(-1) == "!" ||
currentWord.slice(-1) == "?" ||
currentWord.slice(-1) == "?" ||
currentWord.slice(-1) == ";" ||
currentWord.slice(-1) == ":"
) {
答案 0 :(得分:2)
使用这样的正则表达式。如果您不想使用切片,则不需要使用切片。
if (currentWord.match(/[\.,!?;:]$/)) {
alert("matched");
}
这仍然有用......
if (currentWord.slice(-1).match(/[\.,!?;"]/)) {
alert("matched");
}
答案 1 :(得分:1)
您可以创建一个字符数组,然后使用.indexOf()
method。在这种情况下,您只需使用SocketChannel socket = null;
try {
// Accept the next incoming connection from the server
// socket
socket = serverSock.accept();
} catch (IOException ioe) {
//we didn't get a socket
countDownConnection();
// Introduce delay if necessary
errorDelay = handleExceptionWithDelay(errorDelay);
// re-throw
throw ioe;
}
,其中chars.indexOf(currentWord.slice(-1)) > -1
是由字符组成的数组。
chars
或者,您可以使用基本正则表达式和.test()
method。
在这种情况下,您可以使用var currentWord = "hello.",
chars = [".", ",", "!", "?", ";", ":"],
endsInChar = chars.indexOf(currentWord.slice(-1)) > -1;
console.log(endsInChar); // true
,其中/[.,!?;:]$/.test(currentWord)
是字符的字符集,[.,!?;:]
是断言字符串结尾的锚。
$
答案 2 :(得分:0)
虽然可以使用正则表达式,但我更喜欢数组
// 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
}
答案 3 :(得分:0)
许多人更喜欢数组选项,但是,正则表达式是一个非常有用的工具,您也可以使用它们。
例如:
OnClicked
反斜杠的原因是:
var word = prompt("Word?")
alert(/[\.,!\?;:]$/.test(word))
表示任何字符,我们需要文字.
。.
使前面的标记可选,上帝知道?
中的作用。因此,我逃脱了这些角色。