I love coding, coding everyday is the dream! This is one of my projects built with ASP.NET MVC, C# and Postgres to share everything I'm learning on my coding journey. Join me and checkout my portfolio to see more of my projects.
To check if a word or phrase (string) is a palindrome, use a for loop to loop through the string. Start from the end of the string, and place each character into a new variable. Use an if statement to check if the original string is equal to the reversed string in the new variable.
CHECK OUT THE APP >> HERE <<!
CODE EXPLANATION
My Gym was created with the following three functions.
getValues kicks everything off. When the "Time for Push Ups?" button is pressed, it grabs the value of the string from the user by accessing the DOM. It also uses an if-else statement to check if a string was entered. If no string was entered a sweetalert is displayed notifying the user to enter a string. If all is good, it continues to execute checkForPalindrome and displayResults.
checkForPalindrome uses a for loop and Regex on the string received from the user to keep letters and numbers and assign them to a new variable. Another for loop is used to reverse the clean string by grabbing each character from the string starting from the end of the string and adding it to a new variable. An if statement is used to check if the clean string is a palindrome by checking if the reversed clean string is the same as the clean string. If not, it will return 'error' if there is nothing in the clean string variable otherwise, it will let you know the word or phrase entered is not a palindrome. The result is then returned as an array.
displayResults uses an if statement and getElementById to grab the elements that need to be updated so the results from checkForPalindrome can be displayed accordingly.
WHAT I LEARNED
- Regex can be used to easily filter messages to keep only valid characters or search for a particular combination of characters.
- There can be multiple returns in a function to return different values depending on certain conditions.
IMPROVEMENTS
- Combine the two for loops in the checkForPalindrome function
- In displayResults use an object to return the results instead of an array for readability.
0 comments