Skip to content

Instantly share code, notes, and snippets.

@hctilg
Created July 29, 2024 14:46
Show Gist options
  • Save hctilg/432150f69f1e8740d33907b528507f6b to your computer and use it in GitHub Desktop.
Save hctilg/432150f69f1e8740d33907b528507f6b to your computer and use it in GitHub Desktop.
Reverse strings in Javascript
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