James Clarke
James Clarke

Reputation: 31

Palindrome Checker - can't get the function to check the phrase

My Palindrome checker function works for single strings i.e. 'dog' it works, but when it is a phrase i.e. 'nurses run' it does not work! here is my code:

function palindromeCheck(string) {
  return string === string.split('').reverse().join('');

}

Upvotes: 0

Views: 59

Answers (2)

bamtheboozle
bamtheboozle

Reputation: 6436

function palindromeCheck(string) {
  string = string.replace(/\s+/g,'');
  return string === string.split('').reverse().join('');
}

The s+ character means to match any number of whitespace characters (including tabs). The g character means to repeat the search through the entire string. Read about this, and other RegEx modifiers available in JavaScript here.

Upvotes: 3

Ishwar Patil
Ishwar Patil

Reputation: 1736

Try this.

function palindromeCheck(string) {
  string = string.replace(/\s/g, "");
  return string === string.split('').reverse().join('');

}

console.log(palindromeCheck('nurses run'))

Upvotes: 1

Related Questions