Palindromes in Javascript
Here, we are going to achieve palindromes in two ways.
- With inbuilt javascript functions
- Using for loops
Provided test cases
- palindrome(“racecar”) should return true
- palindrome(“test”) should return false
- palindrome(“Racecar”) should return true
- palindrome(“RACECAR”) should return true.
1. With inbuild javascript functions
For this solution, we will use several methods:
- The toLowerCase() method to return the calling string value converted to lowercase.
- The split() method splits a String object into an array of strings by separating the string into sub strings.
- The reverse() method reverses an array in place. The first array element becomes the last and the last becomes the first.
- The join() method joins all elements of an array into a string.
function palindrome(str) {
const originalString = str.toLowerCase();
const reverseString =str.toLowerCase().split('').reverse().join('');
if (originalString === reverseString) {
return true;
} else return false;
}
2. Using for loop
function palindrome(str) {
let originalString = str.toLowerCase();
let reverseString = ''
let array=[]
for(let i=0; iI hope you find it helpful. Please feel free to comment.