1
function palindrome(str) {
  //Clean up string
  var re = '/[^a-z0-9]/gi';
  str=str.toLowerCase();
  str=str.replace(re, '');
  console.log(str);

  //Reverse string and check
  var pstr = str.split('').reverse().join('');
  if (pstr === str){
    return true; 
  }
  return false;
}

palindrome("__Eye");

I'm trying to test a palindrome statement. I'm using https://regex101.com/ to test my regEx statements using sample statements

The function above is an attempt to check if a string value is a palindrome, return true if it is, return false if its not

Palindromes are things like race car where its spelled the same forward and backward

My regex expression is '[^a-z0-9]/gi' which selects all punctuation marks, commas, and spaces in order to delete them using a replace prototype string method. On testing the regex expression it looks fine, see below

enter image description here

problem:

Can someone shed light on what I am doing wrong here? The problem I have is that I am console.log(str) and its not reflecting the correct output. e.g.

__eye input should result in eye output but is not

repl to test code here https://repl.it/JVCf/21

EDIT PROBLEM SOLVED:

Its var re = /[^a-z0-9]/gi; NOT var re = '/[^a-z0-9]/gi';

2
  • race car is not a palindrome. Commented Jul 11, 2017 at 1:43
  • I'm ignoring spaces, commas, punctuation marks when testing palindromes, so in my case race car is a palindrome Commented Jul 11, 2017 at 1:44

1 Answer 1

1

RegEx Pattern is NOT a string

From the MDN documentation:

There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:

/ab+c/i;
new RegExp('ab+c', 'i');
new RegExp(/ab+c/, 'i');

The different methods have their different pros and cons.

function palindrome(str) {
  //Clean up string
  var re = /[^a-z0-9]/g; // note RegEx pattern is not a string
  str=str.toLowerCase();
  str=str.replace(re, '');
  console.log(str);

  //Reverse string and check
  var pstr = str.split('').reverse().join('');
  if (pstr === str){
    return true; 
  }
  return false;
}

palindrome("__Eye");

Sign up to request clarification or add additional context in comments.

1 Comment

ah thank you so much I had just realized this too, I was reading the MDN and didn't see its not a string silly me

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.