Created
July 29, 2024 14:46
-
-
Save hctilg/432150f69f1e8740d33907b528507f6b to your computer and use it in GitHub Desktop.
Reverse strings in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.prototype.reverse = function () { | |
var str = this + ''; | |
// Check the input is invalid | |
if (!str || str.length < 2 || | |
typeof str !== 'string') { | |
return str; | |
} | |
// Take empty array revArray | |
const revArray = []; | |
const length = str.length - 1; | |
// Looping from the end | |
for (let i = length; i >= 0; i--) { | |
revArray.push(str[i]); | |
} | |
// Joining the array elements | |
return revArray.join(''); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment