Atharva Pandey Atharva Pandey - 28 days ago 7
Javascript Question

How to make this Javascript regex more concise?

<code>
function palindrome(str) {
// Good luck!
str=str.toLowerCase();
str=str.replace(/[^\Wa-z0-9]/gi," ");
str=str.replace(/[.,\s]/g, '');
str=str.replace(/\//g, "");
str=str.replace("(", "").replace(")", "").replace("0-0", "").replace(":-", "").replace(":","");
var a=str.split("");
a=a.reverse();
a=a.join("");

if(str===a){
return true;
}
else {
return false;
}
}

palindrome("0_0 (: /-\ :) 0-0");

</code>


Note : I am trying here to remove all the special characters,spaces, and uppercase character and checking that if the passed argument is palindrome or not. I just want to know if there is a way to make the regex concise to only one line, I don't want to have too many replace in here.

Answer
str = str.toLowerCase().replace( /[^a-z0-9]/g, '' );

Will lowercase the string and remove all non alphanumeric characters.

Comments