Pitfalls
String Reversal in place
for(let i =0; i < Math.floor(str.length/2); i++)
[str[i], str[str.length- 1-i]] = [str[str.length- 1-i], str[i]]];
You're attempting to reverse a string in-place using destructuring assignment, which is a great idea in languages like Python or with arrays in JavaScript — but strings are immutable in JavaScript, meaning you cannot modify them directly by index.
This would work if str were an array, but since str[i] is not assignable (because strings are immutable), this will throw an error like:
❌
TypeError: Cannot assign to read only property '0' of string 'hello'
✅ Correct Approach: Convert to Array First
If you want to reverse a string using this kind of logic, convert it to an array first:
function reverseString(str) {
let arr = str.split('');
for (let i = 0; i < Math.floor(arr.length / 2); i++) {
[arr[i], arr[arr.length - 1 - i]] = [arr[arr.length - 1 - i], arr[i]];
}
return arr.join('');
}
✅ Or Simply:
function reverseString(str) {
return str.split('').reverse().join('');
}
Palindrome ignoring case and non-alphanumerics
function isPalindrome(str) {
// Remove non-alphanumeric characters and convert to lowercase
const cleaned = str.replace(/[^a-z0-9]/gi, '').toLowerCase();
// Compare cleaned string to its reverse
return cleaned === cleaned.split('').reverse().join('');
}
OR
function isPalindrome(str) {
let left = 0;
let right = str.length - 1;
while (left < right) {
// Skip non-alphanumeric on the left
while (left < right && !isAlphaNumeric(str[left])) left++;
// Skip non-alphanumeric on the right
while (left < right && !isAlphaNumeric(str[right])) right--;
// Compare characters (case-insensitive)
if (str[left].toLowerCase() !== str[right].toLowerCase()) {
return false;
}
left++;
right--;
}
return true;
}
function isAlphaNumeric(c) {
const code = c.charCodeAt(0);
return (
(code >= 48 && code <= 57) || // 0-9
(code >= 65 && code <= 90) || // A-Z
(code >= 97 && code <= 122) // a-z
);
}