-2

OBJECTIVE Determine whether or not a string is a palindrome ignoring any whitespaces, special characters, and capitalization.

JAVASCRIPT

    function palindrome(str) {
  //remove punctuation, whitespace, capitalization, and special characters from original string - 
  var original = str.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"")
                   .replace(/\s/g," ").toLowerCase();

  //take original sentence and reverse
  var reverse = original.split('').reverse().join('');

  //compare original vs reversed
  if (original == reverse) {
    return true;
  } else {
    return false;
  }

}


palindrome("eye");

QUESTIONS

  1. I've created the aforementioned code from checking online (Palindrome Check). Am I missing anything?
  2. I am using regex to handle punctuation and whitespace and it checks out.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
jonplaca
  • 797
  • 4
  • 16
  • 34

2 Answers2

2

You can join the 2 replace chained methods into 1 by including \s into the character class (and add missing common special characters):

var original = str.replace(/[\s"'.,-\/#!$%\^&*;:{}=\-_`~()\\\[\]@+|?><]/g,"").toLowerCase();
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Thank you - this was actually the solution to the problem I was looking for. With your contribution, the code passed. I am pretty bad with Regex :( – jonplaca May 12 '15 at 02:58
0

Now you can check any string value , either having special char (/n ,/t _ ,# ,% ,2 etc) or not

function palindrome(str) 
    {

        var re = /[\W_]/g; // getting every special character 
    /*  
        [^A-Z] matches anything that is not enclosed between A and Z

        [^a-z] matches anything that is not enclosed between a and z

        [^0-9] matches anything that is not enclosed between 0 and 9

        [^_] matches anything that does not enclose _  

        /[^A-Za-z0–9]/g  or /[\W_]/g
        */

        str = str.toLowerCase().replace(re, ''); // Remove every specal character
        var len = str.length -1; 
        var mid = Number(len/2);

        for ( var i = 0; i < mid; i++ ) 
        {
            if (str[i] !== str[len - i]) 
            {
                return " Not_Palindrome";
            }
        }

        return "Palindrome";
    }


        var inputValue = "m_ad)am";  // input your Value
        var outPutValue = palindrome(inputValue);
        console.log(" the input value  {" + inputValue + "} is :" + outPutValue);
        //the input value  {madam(} is :Palindrome