Check if string is a palindrome

Write a function that takes a string and checks whether it is a palindrome or not. Return true if the given string is a palindrome, otherwise return false.


Palindrome

A Palindrome is a word, phrase, name, or number that reads the same forward or backward.

Palindromes do not account for punctuation, symbols, whitespace or capitalization.

Alphanumeric characters include letters and numbers. All non-alphanumeric characters will be ignored.


Example ...

Enter a string ...

"Kayak" → string to be checked

The function returns true → string is a palindrome, the string reads the same forward as backward.

Enter a string ...

"Kayok" → string to be checked

The function returns false → string is not a palindrome, the string does not read the same forward as backward.

Strings are a sequence of zero or more characters written inside quotes used to represent text.

Strings may consist of letters, numbers, symbols, words, or sentences.

Strings are immutable, they cannot be changed.

Each character in a string has an index.

The first character will be index 0 the second character will be index 1 and so on.

There are two ways to access an individual character in a string.

charAt() method

const str1 = "abc"; string

str1.charAt(0); character at index 0 → "a"

str1.charAt(1); character at index 1 → "b"

str1.charAt(2); character at index 2 → "c"

str1.charAt(3); character at index 3 → "" index not found

Alternatively use at() or slice() methods

bracket notation []

const str2 = "abc"; string

str2[0]; character at index 0 → "a"

str2[1]; character at index 1 → "b"

str2[2]; character at index 2 → "c"

str2[3]; character at index 3 → undefined index not found


Check if a string is a palindrome using ↴

for loop → executes a block of code a number of times.

Regular Expression → patterns used to match character combinations in strings.

toLowerCase() method → returns the value of the string converted to lower case.

replace() method → returns a new string with the value(s) replaced.

length property → return the length of a string.


for loop repeatedly executes a block of code until a specified condition evaluates to false.

The loop runs a block of code a set number of times, defined by an initialization, a condition, and an increment.

for (let x = 0; x < 4; x++) {

console.log(x);

}

Loop variable x is initialized to 0

Condition x < 4 is checked before each iteration.

The loop will continue to run as long as x is less than 4

The loop repeatedly executes a block of code 4 times, from 0 to 3

For each iteration of the loop, the current value of x is printed to the console.

After each iteration, x is incremented by 1 x++

When x reaches 4 the condition evaluates to false, terminating the loop.

0

1

2

3 → printed to console


Regular expressions are patterns used to match character combinations in strings.

The Regular Expression /[^A-Za-z0-9]/g defines a regular expression that matches any character that is NOT an upper case or lower case letter or a digit.

^ caret symbol at the beginning of the square brackets, negates the character set.

[^A-Z] matches anything that is NOT enclosed between A and Z

[^a-z] matches anything that is NOT enclosed between a and z

[^0-9] matches anything that is NOT enclosed between 0 and 9

/g flag indicates that the search should be global, meaning it will find all occurrences.


replace() method searches a string for a value or a regular expression and returns a new string with the value replaced.

If pattern is a string, only the first occurrence will be replaced.

syntax

string.replace(pattern, replacement)

const str3 = "hello world";

str3.replace("hello", "HELLO"); replace "hello" with "HELLO"

returns ↴

"HELLO world"

const str4 = "ABCDEF";

str4.replace("B", ""); replace "B" with "" empty string

returns ↴

"ACDEF""B" removed from string


toLowerCase() method converts all letters to lower case. The original string is unchanged.

const str5 = "hELlo wORLd";

str5.toLowerCase(); returns ↴

"hello world" → lower case


Combining a regular expression with the toLowerCase() and replace() methods ↴

const str6 = "%HELLO +/- 12#34 @!^$"; → string

const regex = /[^A-Za-z0-9]/g; → regular expression

str6.toLowerCase().replace(regex, ""); returns ↴

"hello1234" converted to lower case and all non-alphanumeric characters removed


length property returns the number of characters in a string.

const str7 = "Hello World";

str7.length; returns ↴

11 → there are 11 characters in the string

Strings are zero indexed, the first character will be index 0

The last character will be at index length -1

To find the last index in a string.

const str8 = "Hello World";

str8.length - 1; returns ↴

10 → end index of string


Initialize a variable to hold the string to check for a Palindrome.

const string1 = "Kayak"; → user input


Define a function palindrome to check if a string is a Palindrome.

function palindrome(str) {}

The function takes a string as input str and returns true if the given string is a palindrome, otherwise returns false.

Convert str to lower case.

const lowerStr = str.toLowerCase() lowerStr

Use a regular expression to match non-alphanumeric characters.

const regEx = /[^A-Za-z0-9]/g regEx

Remove non-alphanumeric characters from lowerStr

const cleanedStr = lowerStr.replace(regEx, "") cleanedStr

Get the length of cleanedStr

const strLength = cleanedStr.length strLength

Strings are zero indexed, so last index will be length - 1

Get the end index of cleanedStr for comparison.

const endIndex = strLength - 1 endIndex

Loop through the first half of cleanedStr strLength / 2 (rounded up if odd number)

for (let x = 0; x < strLength / 2; x++) {}

cleanedStr is compared character by character from both ends.

if (cleanedStr[x] !== cleanedStr[endIndex - x])

If characters do not match, return false.

return false function terminates

If all characters match, return true.

return true

If the comparison function returns true, the string is a palindrome

If the comparison function returns false, the string is not a palindrome


Call the function with ↴

palindrome(string1);


Check if string is a palindrome

String to be tested: "kayak"

Loop through the first half of the string.

Compare string, character by character, from both ends.

Iteration 1:

[x] = 0 "k" [endIndex - x] = 4 "k" "k" === "k"

Iteration 2:

[x] = 1 "a" [endIndex - x] = 3 "a" "a" === "a"

Iteration 3:

[x] = 2 "y" [endIndex - x] = 2 "y" "y" === "y"

Loop completes ↴

"kayak" is a palindrome

String to be tested: "kayok"

Loop through the first half of the string.

Compare string, character by character, from both ends.

Iteration 1:

[x] = 0 "k" [endIndex - x] = 4 "k" "k" === "k"

Iteration 2:

[x] = 1 "a" [endIndex - x] = 3 "o" "a" === "o"

End function execution ↴

"kayok" is not a palindrome


Check if string is a palindrome.

const string1 = "Kayak";

function palindrome(str) {

const regEx = /[^A-Za-z0-9]/g;

const lowerStr = str.toLowerCase();

const cleanedStr = lowerStr.replace(regEx, "");

const strLength = cleanedStr.length;

const endIndex = strLength - 1;

for (let x = 0; x < strLength / 2; x++) {

if (cleanedStr[x] !== cleanedStr[endIndex - x]) {

return false;

}

}

return true;

}

call function

palindrome(string1); returns ↴

true


Alternative regular expression pattern ↴

/[^A-Za-z0-9]/g same as ↴

/[^a-z0-9]/gi case-insensitive


Alternative without using variables ↴

const string2 = "Kayak";

function palindrome2(str) {

const regex = /[^A-Za-z0-9]/g;

const cleanedStr = str.toLowerCase().replace(regex, "");

const strLength = cleanedStr.length;

for (let x = 0; x < strLength / 2; x++) {

if (cleanedStr[x] !== cleanedStr[strLength - 1 - x]) {

return false;

}

}

return true;

}

call function

palindrome2(string2); returns ↴

true


Valid Palindromes ↴

A man, a plan, a canal. Panama

Never odd or even

Pull up if I pull up

Stressed desserts

Evil, olive!

Race car

Radar

Kayak

Check for palindrome