Skip to main content

Palindrome Checker回文检查

 Return true if the given string is a palindrome. Otherwise, return false.


A palindrome is a word or sentence that's spelled the same way both forward and backward, ignoring punctuation, case, and spacing.


Note: You'll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything into the same case (lower or upper case) in order to check for palindromes.


主要思路是,把字符串转换为一个数组,然里利用数组的reverse()方法,得到一个新的数组,这个新的数组再合成字符串,和原来的字符串进行比较。


function palindrome(str) {
  var pattern = /[^a-z0-9A-Z]/gi;
  var newstr = str.replace(pattern,"").toLowerCase();
  console.log(newstr);
  var newarr = newstr.split("").reverse();
  console.log(newarr);
  var reversedStr = newarr.join("");
  console.log(reversedStr);
  if (reversedStr==newstr)
  {
    return true;
  } 

  return false;
}

palindrome("eye");

Comments

Popular posts from this blog

span[class~="sr-only"]

  The  span[class~="sr-only"]  selector will select any  span  element whose  class   includes   sr-only . Create that selector, and give it a  border  property set to  0 . span [ class ~= "sr-only" ] {    border:   0 ; }

Use Recursion to Create a Range of Numbers

  function   rangeOfNumbers ( startNum ,  endNum ) {    if ( startNum <= endNum )   {      const   arrNumber  =  rangeOfNumbers ( startNum ,  endNum - 1 );      arrNumber . push ( endNum );      return   arrNumber ;   }    else  {      return  [];   }       }; console . log ( rangeOfNumbers ( 6 , 8 ));//[6,7,8] console . log ( rangeOfNumbers ( 3 , 12 )); //[ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]

About the Little Lemon receipt maker exercise

 My homework and exercise of the lesson "About the Little Lemon receipt maker exercise" of the class "programming with Javascript" on coursera. const menu = [     {         Dish : "Italian pasta" ,         price : 9.55     },     {         Dish : "Rice with veggies" ,         price : 8.65     },     {         Dish : "Chicken with potatoes" ,         price : 15.55     },     {         Dish : "Vegetarian Pizza" ,         price : 6.45     } ]; function receiptMaker ( arr , bool ) {     if ( bool == false )     {         console . log ( "Prices without tax:" );         arr . forEach ( element => {             console . log ( `Dish: ${ element . Dish } Price (incl.tax):$ ${ element . price } ` );                     });     }     else     {         console . log ( "Prices with 20% tax:" );         arr . forEach ( element => {             console . log ( `Dish: ${ element . Dish } Price (inc