Search code examples
javascriptregexpalindrome

How to match multiple strings using regular expression?


I have a bunch of strings to match for Bonfire: Palindrome in FreeCodeCamp The strings are:

  • eye
  • racecar
  • not a palindrome
  • A man, a plan, a canal. Panama
  • nope
  • almostomla
  • My age is 0, 0 si ega ym.
  • 1 eye for of 1 eye.
  • 0_0 (: /-\ :) 0-0

My Code:

function palindrome(str) {


  var newstr = str.replace(/[^\w_-]/g,"").toLowerCase();
  var num = newstr.length;
  for(var i=0;i<=Math.floor(num/2);i++)  
    {
      if(newstr[i]!==newstr[num-i])
        {

          return newstr;

       }
    }

  return true;
}

What could be wrong in the if statement? the return of the string is alright.. Just can't wrap my head around these Regular expressions?

My current regular expression:

var newstr = str.replace(/[^\w_-]/g,"").toLowerCase();

matches almost all the strings but the last one. Where am I going wrong?


Solution

  • So while the answers were useful, they did not provide a correct regular expression. Shoot out to @Barmar for pointing at the right direction. This is my regular expression.

    var newstr = str.replace(/[\W_]/g,'').toLowerCase();
    

    The full code for Palindrome in FCC:

    function palindrome(str) {
    
    
      var newstr = str.replace(/[\W_]/g,'').toLowerCase();
      var num = newstr.length;
      for(var i=0;i<=Math.floor(num/2);i++)  
        {
          if(newstr[i]!==newstr[num-1-i])
            {
    
              return false;
    
           }
        }
    
      return true;
    }
    
    
    
    palindrome("0_0 (: /-\ :) 0-0");