EN
JavaScript - reverse string (English letters)
4
points
In this short article, we would like to show you how reverse strings using JavaScript.
In practice string reversion problem is very comples when we work on emojis, surrogate characters,Ā Asian characters, etc. Some solutions for that kind of strings reversion was shown in this article.
Ā
In the below you can find different solutions.
1. split-reverse-join example
// ONLINE-RUNNER:browser;
function reverseString(text) {
var characters = text.split('');
var reversion = characters.reverse();
return reversion.join('');
}
// Usage example:
var text = 'ABC';
var reversion = reverseString(text);
console.log(reversion); // CBA
Warning: this solutuionĀ doesn't work with allĀ emojis andĀ Asian characters.
Output:
CBA
2. Reverse string with iteration example
2.1. for...of solutuion
This solution should be used when we work on more comples unicode characters likeĀ emoji.
// ONLINE-RUNNER:browser;
function reverseString(text) {
let result = '';
for (const character of text) {
result = character + result;
}
return result;
}
// Usage example:
var text = 'Hi there ! 💻🙂😀😋';
var reversion = reverseString(text);
console.log(text); // Hi there ! 💻🙂😀😋
console.log(reversion); // 😋😀🙂💻 ! ereht iH
Warnings:
- this solution works under ES6+,
- this solutuionĀ doesn't work with allĀ emojis andĀ Asian characters.
2.2. classic for solution
// ONLINE-RUNNER:browser;
function reverseString(text) {
var result = '';
for(var i = text.length - 1; i > -1; --i) {
result += text[i];
}
return result;
}
// Usage example:
var text = 'ABC';
var reversion = reverseString(text);
console.log(reversion); // CBA
Warning: this solutuionĀ doesn't work with allĀ emojis andĀ Asian characters.
3. String.prototype.reverse
method prototype
// ONLINE-RUNNER:browser;
if (String.prototype.reverse == null) {
String.prototype.reverse = function() {
var result = '';
for (var i = this.length - 1; i > -1; --i) {
result += this[i];
}
return result;
}
}
// Usage example:
var text = 'ABC';
var reversion = text.reverse();
console.log(reversion); // CBA
Note: in this case
String
object isĀ extended of new reverse method.
Warning: this solutuionĀ doesn't work with allĀ emojis andĀ Asian characters.
Output:
CBA
Ā