Languages
[Edit]
EN

JavaScript - how to reverse string?

1 points
Created by:
Elmer-Li
396

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

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

// ONLINE-RUNNER:browser;

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

    return result;
}


// Usage example:

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

console.log(reversion);  // ...txet ym si sihT

Output:

...txet ym si sihT

2. Reverse string with iteration example

// 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 = 'This is my text...';
var reversion = reverseString(text);

console.log(reversion);  // ...txet ym si sihT

Output:

...txet ym si sihT

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 = 'This is my text...';
var reversion = text.reverse();

console.log(reversion);  // ...txet ym si sihT

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

Output:

...txet ym si sihT

JavaScript - String (popular problems)

JavaScript - reverse string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join