Vincent Tang
Vincent Tang

Reputation: 4170

Incorrect regex expression for Javascript

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';

Upvotes: 0

Views: 143

Answers (1)

Fred Gandt
Fred Gandt

Reputation: 4312

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");

Upvotes: 1

Related Questions