Check if string is a Palindrome (Ruby)

Straight to the task:

# Write a method that takes a string and returns true if it is a
# palindrome. A palindrome is a string that is the same whether written
# backward or forward. Assume that there are no spaces; only lowercase
# letters will be given.

According to our task, we should assume that our string contains only one word. An easy way to find out if string is a palindrome is to check whether the string and the reversed string are equal.

def palindrome?(string)
if string == string.reverse
return true
puts “String is not a palindrome”

Now we call the method for both cases:

# “String is not a palindrome”
# true

Done :)

On Freecodecamp there was a similar task to check if the string is a palindrome using Javascript. This time we do not assume that string contains only 1 word. Here is a list of tests we need to pass:

You’ll need to remove all non-alphanumeric characters (punctuation, spaces and symbols) and turn everything lower case in order to check for palindromes.
palindrome("eye") should return a boolean.
palindrome("eye") should return true.
palindrome("_eye") should return true.
palindrome("race car") should return true.
palindrome("not a palindrome") should return false.
palindrome("A man, a plan, a canal. Panama") should return true.
palindrome("never odd or even") should return true.
palindrome("nope") should return false.
palindrome("almostomla") should return false.
palindrome("My age is 0, 0 si ega ym.")should return true.
palindrome("1 eye for of 1 eye.") should return false.
palindrome("0_0 (: /-\ :) 0-0") should return true.
palindrome("five|\_/|four") should return false.

We also have a special case of:

palindrome("_eye") should return true.

This is why or regexp should look like /[\W_]/.

function palindrome(str) {
//\W removes all non-alphanumeric characters, 'g' flag stands for global search
var re = /[\W_]/g;

var strLow = str.toLowerCase().replace(re, '');
var reverseStr = strLow.split('').reverse().join('');

if (strLow === reverseStr) {
return true;
} else {
return false;