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


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.";

Currently I am getting this:

".yllufepoh ,nuf si sihT"

When I want to return this:

"sihT si nuf, yllufepoh."


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 *