Languages
[Edit]
EN

JavaScript - how to reverse string?

1 points
Created by:
Kate_C
19790

In JavaScript it is possible to reverse string in following way.

1. Reverse string with split-reverse-join operations example

function reverseString(text) {
    var array = text.split('');
    var reversion = array.reverse();
    var result = reversion.join('');

    return result;
}

Example:

var text = 'This is my text...';
var reversion = reverseString(text);

console.log(reversion);

Output:

...txet ym si sihT

2. Reverse string with iteration example

function reverseString(text) {
    var result = '';

    for(var i = text.length - 1; i > -1; --i) {
        result += text[i];
    }

    return result;
}

Example:

var text = 'This is my text...';
var reversion = reverseString(text);

console.log(reversion);

Output:

...txet ym si sihT

3. String.prototype.reverse method prototype

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;
    }
}

Note: in this case String object is extended of new reverse method.

Example:

var text = 'This is my text...';
var reversion = text.reverse();

console.log(reversion);

Output:

...txet ym si sihT

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join