Check for Palindromes/ Regular Expression Multiple Patterns?

Tell us what’s happening:
I already solved the problem.

My question is, if it is possible to shorten my code for searching for non-alphanumeric characters, underscore characters, and whitespace characters.

Can I make a Regular Expression with more than one pattern inside it?
For example:
var regEx = /pattern,2ndpattern,3rdpattern/g;

Is this possible?

Your code so far

function palindrome(str) {
  // Good luck!
  //If any non-alphanumeric characters are present remove them.
var newstr = str.replace(/_/g, '');
   newstr = newstr.replace(/\s/g,'');
   newstr = newstr.replace(/\W/g,'');
   newstr = newstr.toLowerCase();
var endOfStr = newstr.length;
  



palindrome("race1 _car!##@#$DSFASF");

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/check-for-palindromes

You can use square brackets to search for more than one type of character, eg.

.replace(/[_\s]/, " ")

I use a regex tester to build up my regular expressions, you might want to check out https://regex101.com/#javascript as it will highlight what the regex is doing as you work through it.

Hope this helps

1 Like