Languages
[Edit]
EN

JavaScript - how to reverse string?

1 points
Created by:
Kate_C
2878

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

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.