The Code
// step 1: receiving and responding to the user's string
function getValue() {
let userInput = document.getElementById('message').value;
if (userInput.length < 2) {
// making the alert invisible if already showing on the screen
let alert = document.getElementById('alert')
alert.classList.add('invisible');
Swal.fire({
icon: 'error',
backdrop: false,
title: 'Step-On-No-Pets',
text: 'Please, enter at least 2 characters.',
})
} else {
let isPalindrome = checkForPalindrome(userInput);
let userMessageReversed = reverseString(userInput);
// creating an object that handles everything
let results = {
input: userInput,
reversed: userMessageReversed,
isPalindrome: isPalindrome
}
// finally displaying the results on the screen
displayResults(results)
}
}
// step 2: the function that will reverse our string.
function reverseString(inputString) {
// You can treat a string just like an array
let result = '';
// decrementing for loop
for (let index = inputString.length - 1; index >= 0; index--) {
result += inputString[index];
}
// return the string
return result;
}
// step 3: determining whether a string is a palindrome
function checkForPalindrome(input) {
// take the user input and reverse it
let lowerCaseInput = input.toLowerCase()
lowerCaseInput = lowerCaseInput.replace(/[^a-z0-9]/gi, '')
let reversed = reverseString(lowerCaseInput);
// see if the reversed string is the same as the user input
let isPalindrome = reversed == lowerCaseInput
// return a value indicating whether it is or not a palindrome
return isPalindrome;
}
// step 4: displaying a message to the user to show
// whether their string is a palindrome or not
function displayResults(results) {
let alert = document.getElementById('alert');
alert.classList.remove('invisible', 'alert-success', 'alert-danger');
if (results.isPalindrome) {
// make the alert green
alert.classList.add('alert-success');
// Changing the header message for success
alert.querySelector('h4').innerHTML =
'Well done! You entered a Palindrome!';
} else {
// make the alert red
alert.classList.add('alert-danger');
// Changing the header message for failure
alert.querySelector('h4').innerHTML = "Sorry My Friend! It's not a palindrome";
}
let resultInput = results.input.replace(/[^a-zA-Z0-9 ]/g, '')
let resultReversed = results.reversed.replace(/[^a-zA-Z0-9 ]/g, '')
// display the user input vs the reverse message
alert.querySelector(
'p'
).innerHTML = `Your message was: <b>${resultInput}</b><br />Your reversed message is: <b>${resultReversed}</b>`
}
The Bonus
// BONUS 1:
// determining whether a string is a palindrome using array notation
function checkForPalindromeB(userInput) {
// turn the string into an array
// split a string into multiple sub-strings and return them in the form of an array
let characters = userInput.split('')
let arrayRuselt = []
// using a decrementing for loop
for (let index = userInput.length - 1; index >= 0; index--) {
let letter = characters[index]
arrayRuselt.push(letter)
}
// turn the new array back into a string
let newArray = arrayRuselt.join('')
// palindrome or not
if (newArray.toLowerCase() == userInput.toLowerCase()) {
return newArray.toLowerCase()
} else {
return false
}
}
// BONUS 2:
// determining whether a string is a palindrome using string only
function checkForPalindromeC(userInput) {
let stringResult = ''
// using a decrementing for loop
for (let index = userInput.length - 1; index >= 0; index--) {
stringResult += userInput[index]
}
if (userInput.toLowerCase() == stringResult.toLowerCase()) {
return stringResult.toLowerCase()
}
}
// BONUS 3:
// check if the words can be compared to itself using reverse() array method
function checkForPalindromeD(userInput) {
let resultStr = Array.from(userInput.toLowerCase())
resultStr = resultStr.reverse().join('')
if (resultStr == userInput.toLowerCase()) {
return resultStr
}
}
How the code works behind the scene!
Before jumping into VSCode and starting to write code, I needed a plan and at that moment I started by asking myself questions about the problem that I needed to solve and I managed to divide the problem into steps. For this problem I actually developed four steps.
- Receiving the user input and responding to the user's back with the final answer.
- Creating a function that will reverse the giving string.
- Determining whether a string is a palindrome or not.
- And finally, displaying a message to the user using our HTML page that was build specially for this effect.
The four steps in action!
getValue()
So, regarding this function, it only collects the text
that we need and returns the result. To make my task
easier I used an object in which I store useful
information to be able to access it if necessary or at
least use it in the function which has the task of
displaying the result, in this case
displayResults
which you will see later.
Finally, to ensure some of the validity of the
information we receive from the
getValue
function, I use the help of
sweetalert2.
reverseString()
The reverseString
function has only one
responsibility: reverse the received text. Note that
there are several ways to do this, and many developers
would try to use the array method, but as far as I am
concerned I know that strings have one thing in common
with arrays, and that is the indexing. Which allows me
to access each character without writing too much code.
To do this I create an empty string variable just like I
could do by creating an empty array. I use a for loop to
access the
length of the message -1, knowing that the indexing of the string starts from
0, set my condition for the loop to then decrement by 1
at each iteration and concatenate the letters in my
empty string variable. And finally return this variable
for later use.
checkForPalindrome()
The checkForPalindrome
function is
responsible for taking an input and converting it to
lowercase, then removing the symbols that could
accompany the text to replace them with an empty string,
using the buildin javascript method
replace
and a regular expression. In this
function we call our reverseString
which
has the sole purpose of turning the text backward, then
we ensure that the two texts are identical by comparing
the input that the
checkForPalindrome
function receives with
that returned by the
reverseString
function, so if these two are
the same it's a palindrome. At the end we return the
result for later use.
displayResults()
The displayResults
function aims to display
the long-awaited result to the user and for this we use
a template tag. Before going any further, what is this
famous template tag in HTML?
HTML <template>
Tag:
The template
tag is an HTML5 element that
allows you to hold client-side content that you don't
want to be rendered when the page loads. The content
inside a template
tag is not displayed, and
it can be used as a template to clone and insert into
the document later using JavaScript. This is
particularly useful for storing reusable content that
can be dynamically added to the DOM.
Let's get back to our displayResults function! We access
an alert that we created using our template tag, then
remove the class that made our alert invisible in order
to display the result and change the classes that allow
us to change the colors when the message is a palindrome
or not. So if the message is a palindrome we display a
success message and otherwise we display a completely
different message using our if
statement.
At this level, I also prefer to remove the symbols that
were passed with the text during display by using the
regular expression
. In the end, when displaying the
alert I present the input message and the reversed
message to prove that the message is a palindrome or
not.
BONUS SECTION!!!
In the bonus section below I gave you other ways to do the same thing, which proves that in programming there are many ways to solve a problem, and that it all depends on your approach. This is why you should always try to divide the problem into small parts that will help you achieve your goal. See the bonus section to test the codes and try to understand what is happening.