Top community members
All Wiki Articles Create Wiki Article

In the past we had a dream,
to have place where we could share IT knowledge,
to ask questions without fear that someone will judge us.

Now we are a group of people who make this dream come true. ❤ 💻

If you think sharing knowledge and helping other is valuable.

join our community - Click here

JavaScript - how to reverse string?

0 contributions
1 points

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

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more