JavaScript Program to Check Whether the String is Symmetrical or Not
Last Updated :
20 Sep, 2023
In this article, we will see how to check whether the given string is symmetric or not. The symmetrical string is one that is similar from the starting to mid and mid to end.
Example:
Input: khokho
Output:
The entered string is symmetrical
Input: madam
Output:
The entered string is not symmetrical
Input:amaama
Output:
The entered string is symmetrical
Methods to Check Whether the Given String is Symmetric or Not
- Naive Method
- Using string slice Method
- Using substring Method
Method 1: Naive method using loops
Example:
Javascript
let str = "abcdabc" ;
let mid = Math.ceil(str.length / 2);
for (let i = 0; i + mid < str.length; i++) {
if (str[i] !== str[mid + i])
return console.log( "String is not Symmetric" );
}
console.log( "The Given string is symmetric" );
|
Output
The Given string is symmetric
Method 2: Using the slice method
Example:
Javascript
let str = "abcdabc" ;
mid = Math.floor(str.length / 2);
if (
str.slice(0, mid) ===
str.slice(mid + (str.length % 2 === 0 ? 0 : 1))
)
console.log( "The given string is Symmetric" );
else {
console.log( "The given string is Not Symmetric" );
}
|
Output
The given string is Symmetric
Method 3: Using substring method
Javascript
let str = "abcdabc" ;
mid = Math.floor(str.length / 2);
if (
str.substring(0, mid) ===
str.substring(mid + (str.length % 2 === 0 ? 0 : 1))
)
console.log( "The given string is Symmetric" );
else {
console.log( "The given string is Not Symmetric" );
}
|
Output
The given string is Symmetric
Share your thoughts in the comments
Please Login to comment...