在一个句子中识别回文

时间:2017-02-03 02:20:54

标签: javascript jquery html palindrome

我在这里找到的很多解决方案在检查字符串是否为回文后给出了真或假。我有一个函数来检查字符串是否是回文:

    function palindrome(myString){

    /* remove special characters, spaces and make lowercase*/
    var removeChar = myString.replace(/[^A-Z0-9]/ig, "").toLowerCase();

    /* reverse removeChar for comparison*/
    var checkPalindrome = removeChar.split('').reverse().join('');

    /* Check to see if myString is a Palindrome*/
    if(removeChar === checkPalindrome){

    document.write("<div>"+ myString + " is a Palindrome <div>");
    }else{

    document.write("<div>" + myString + " is not a Palindrome </div>");
    }
    }

    palindrome("Oh who was it I saw, oh who?")
    palindrome("Madam")
    palindrome("Star Wars")

但这不是我想要的。它只是检查字符串是否是回文。我想更新函数,以便识别句子中的所有回文而不是给它真或假。所以,如果有这样一句话 - “女士和约翰中午出去了”它会在那句话中列出回文 - “女士,中午”

任何帮助都将不胜感激!

2 个答案:

答案 0 :(得分:1)

&#13;
&#13;
function findPalindromes(str, min) {
  min = min || 3;
  var result = [];
  var reg = str.toLowerCase();
  var reg = reg.replace(/[^a-z]/g, ''); // remove if you want spaces
  var rev = reg.split("").reverse().join("");
  var l = reg.length;
  for (var i = 0; i < l; i++) {
    for (var j = i + min; j <= l; j++) {
      var regs = reg.substring(i, j);
      var revs = rev.substring(l - j, l - i);
      if (regs == revs) {
        result.push(regs);
      }
    }
  }
  return result;
}

var str1 = "Madam and John went out at noon";
console.log(str1, findPalindromes(str1));
var str2 = "\"Amore, Roma\" and \"There's no 'x' in Nixon\" are palindromes.";
console.log(str2, findPalindromes(str2));
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

function findPalindromes(sentence) {
  const words = sentence.replace(/[^\w\s]/gi, '').split(' ');
  const palindromes = words.filter(isPalindrome);
  return palindromes;
}

function isPalindrome(word) {
  if (word.length <= 0) return false;
  word = word.toLowerCase();
  for (let i = 0; i < word.length / 2; i++) {
    if (word[i] !== word[word.length - 1 - i]) return false;
  }
  return true;
}

https://jsfiddle.net/ewezbz22/1/