'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.";
str.reverse();

Currently I am getting this:

".yllufepoh ,nuf si sihT"

When I want to return this:

"sihT si nuf, yllufepoh."


Solution 1:[1]

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(" "));

Solution 2:[2]

You could reverse each word instead of the whole string, but you have to keep spaces, periods etc seperate, so a word boundary is needed

String.prototype.reverse = function () {
    return this.split(/\b/g).map(function(word) {
        return word.split('').reverse().join('');
    }).join('');
}

var str = "This is fun, hopefully.";

document.body.innerHTML = str.reverse();

Note that this moves the comma one space as it gets the comma and the space in one boundary and swaps them. If the comma needs to stay in the same spot, split on spaces as well, and change the regex to /(\b|\s)/g

Solution 3:[3]

You can imagine that you receive a stream of letters and you have to construct words based on some separators (like: spaces, commas, dashes .etc).

While reading each character you keep constructing the word in reverse.

When you hit any separator you finished the word.

Now you just add it to the result and append the separator (this way the separators will not be put at the beginning of the word, but at the end).

Here is an example:

const inputString = "HELLO, Welcome to Google's meeting. My name is Jean-Piere... Bye";
console.log('Normal words: ', inputString);

const result = reverseWords(inputString);
console.log('Words reversed: ', result);

function reverseWords(str='', separators=' ,.-') {
    let result = '';
    let word = '';

    for (const char of str) {
        if (separators.includes(char)) {
            result += word + char;
            word = '';
        } else {
            word = char + word;
        }
    }
    
    // Adds last remaining word, if there is no separator at the end. 
    result += word;

    return result;
}

Solution 4:[4]

const str = "This is fun, hopefully.";

function reverseWords(str){
   const tempArr= str.split(" ")
   let reversedTempArr=''
   for(let i=0; i<tempArr.length;i++){
     let tempStr=''
     for(let j=tempArr[i].length-1;j>=0;j--){
       tempStr += tempArr[i][j]
     }
     reversedTempArr += tempStr+ " "
   }
   return reversedTempArr
}

console.log(reverseWords(str))

Solution 5:[5]

You can reverse each word in a string in squence by splitting that word in to an array of words and then reversing each word and storing it in a new array and then joining that array as shown below.

//1) Reverse words
function reverseWords(str) {
    // Go for it
    let reversed;
    let newArray=[];
    reversed = str.split(" ");
    for(var i = 0;i<reversed.length; i++)
    {
        newArray.push(reversed[i].split("").reverse().join(""));     
    }
    return newArray.join(" ");
}
let reversedString = reverseWords("This is fun, hopefully.");
console.log("This is the reversed string : ",reversedString);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mathias Bynens
Solution 2
Solution 3
Solution 4 Iamwafiq
Solution 5 bilalmohib