Search code examples
javascriptregexstringreplacepalindrome

Regular Expressions Javascript


function palindrome(str) {
  var cleanStr = str.replace(/_\W/g, "");
  return cleanStr;
}

palindrome("_eye");

The above mentioned code returns "_eye" as the output. I might be missing something very obvious but why isn't the regular expression working? The intent is to remove any characters that are not words or numbers.


Solution

  • You need to use brackets around the characters. Also, put a + after the brackets to remove continuous occurence of such characters.

    function palindrome(str) {
      var cleanStr = str.replace(/[_\W]+/g, "");
      return cleanStr;
    }
    console.log(palindrome("_eye"));