[SOLVED] Reverse words in array string matching punctuation in Javascript

Issue

How do I reverse the words in this string including the punctuation?

String.prototype.reverse = function () {
    return this.split('').reverse().join('');
}

var str = "This is fun, hopefully.";
str.reverse();

Currently I am getting this:

".yllufepoh ,nuf si sihT"

When I want to return this:

"sihT si nuf, yllufepoh."

Solution

Simply reversing the string wont give the solution.

  1. Get each word.
  2. Reverse It
  3. Again rejoin
var str = "This is fun, hopefully.";
alert(str.split("").reverse().join("").split(" ").reverse().join(" "));

Answered By – Tushar

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *