In this example, you will learn how to check if the string is palindrome or not in JavaScript.
Basically, we are going to learn different ways to checks if the string is palindrome or not in JavaScipt.
A string is a palindrome if it is read the same from forward or backward. For example, dad reads the same either from forward or backward. So the word dad is a palindrome. Similarly, madam is also a palindrome.
JavaScript Checks if the String is Palindrome or not
Two ways to check if String is Palindrome or not:
- With built-in functions
- With a for loop and straight forward regex
main.js
Let's create a main.js file and add the following code to it:
/* 1. With built in functions
\W matches any non-word character (equal to [^a-zA-Z0-9_])
_ matches the character _ literally (case sensitive)
*/
function isPalindrome(str) {
return str.replace(/[\W_]/g, '').toLowerCase() ===
str.replace(/[\W_]/g, '').toLowerCase().split('').reverse().join('');
}
//2. With a for loop and straight forward regex
function isPalindromeUsingLoop(str) {
var regex = /[^A-Za-z0-9]/g;
str = str.toLowerCase().replace(regex, '');
var len = str.length;
for (var i = 0; i < len/2; i++) {
if (str[i] !== str[len - 1 - i]) {
return false;
}
}
return true;
}
// testing
console.log(isPalindrome("racecar"));
console.log(isPalindromeUsingLoop("racecar"));
Note that the comments in the above code are self-descriptive.
index.html
To test JavaScript code, let's create an HTML file named index.html and add the following code to it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="main.js"></script>
</body>
</html>
Note that we have included the main.js file as an external JavaScript file:
<script src="main.js"></script>
Run index.html in Browser
Run above index.html file in browser and open dev tools console to see the output of the JavaScript code:
true
true
Related JavaScript Examples
- How to Empty an Array in JavaScript //Popular
- JavaScript Utility Methods //Popular
- Best JavaScript Utility Libraries //Popular
- Check if Map is Null or Empty in Java //Popular
- JavaScript LocalStorage Methods - setItem(), getItem(), removeItem() clear() and key() Example //Popular
Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours
Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course
Comments
Post a Comment