在Javascript

时间:2017-04-29 19:56:40

标签: javascript regex palindrome

我目前正在制作一本高级记忆簿我的英语课,而且因为我是书呆子,所以我会在其中加入一些代码。好吧,我在代码中使用正则表达式时遇到了一些麻烦。 我的整个代码:

//For future reference, "alert(*parametes*)" will make an alert box with the parameters inside it.

//Asks you to enter a phrase and stores your answer.
var phrase = prompt("Enter a phrase to be checked for palindrome.").toLowerCase()
//Creates the entered phrase backwards.
var phraseBackwards = ""
for (var x in phrase) {
  phraseBackwards += phrase[(phrase.length - 1) - x]
}
//Checks to see if the new phrase is a palindrome.
if (phraseBackwards == phrase) {
  alert("The phrase you entered was a palindrome.")
}
//This happens if the preavious condition was false.
else {
  //Checks if the new phrase is a palindrome without spaces.
  if (phraseBackwards.replace("/\s+/g", '') == phrase) {
    alert("The phrase you entered would have been a palindrome, had it not had spaces")
  } else {
    //Checks to see if the phrase you entered, even without spaces, is not a palindrome.
    if (phraseBackwards.replace(/\s+/g, '') != phrase) {
      alert("The phrase you ented was not a palindrome.")
    }
  }
}

无法正常运作的特定部分:

//Checks if the new phrase is a palindrome without spaces.
if (phraseBackwards.replace(/\s+/g, '') == phrase) {
  alert("The phrase you entered would have been a palindrome, had it not had spaces")
}

我意识到我的一些代码可能不是最优的但是我想赶快完成因为我拖延到最后一分钟。

2 个答案:

答案 0 :(得分:0)

因此,在我的编辑中需要注意几点。

首先,您需要使用以下内容从初始短语中删除所有非单词字符:replace(/\W/g, "")

然后反转字符串:phrase.split("").reverse().join("")

然后检查是否phraseBackwards == phrase

注意:用于反转字符串的代码有效。但考虑到你的用途,我认为你可能想缩短它。



//For future reference, "alert(*parameters*)" will make an alert box with the parameters inside it.

//Asks you to enter a phrase and stores your answer.
var phrase = prompt("Enter a phrase to be checked for palindrome.").toLowerCase().replace(/\W/g, "");

//Creates the entered phrase backwards.
var phraseBackwards = phrase.split("").reverse().join("");
//Checks to see if the new phrase is a palindrome.
if (phraseBackwards == phrase) {
	alert("The phrase you entered was a palindrome.");
}
//This happens if the previous condition was false.
else {
	alert("The phrase you ented was not a palindrome.");
}




答案 1 :(得分:-2)

没有空格的phraseBackwards不能= =原始短语,因为原文有空格。从原始短语中删除空格。 - Jeremy Thille