3

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."
thefourtheye
  • 233,700
  • 52
  • 457
  • 497

5 Answers5

4

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

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • The position of the comma is shifted. And for that matter, the position of any punctuation marks will be shifted. – Yellen Apr 21 '15 at 06:31
  • There needs to be check for punctuation only words when before doing this word.split('').reverse() – Yellen Apr 21 '15 at 06:33
  • Only if the punctuation has a leading or following space. In my mind, commas and periods should be shifted, but if that's not what the OP wants I've already added a solution for that. – adeneo Apr 21 '15 at 06:33
  • I definitely like this solution. Don't take me wrong. OP want "sihT si nuf, yllufepoh." but this solution returns sihT si nuf ,yllufepoh. : Note the position of the commas – Yellen Apr 21 '15 at 06:34
  • 1
    And note what it says in the answer, where I actually explain the comma and propose a solution for it. – adeneo Apr 21 '15 at 06:35
  • Well, clearly the OP wanted something else, but thanks ! – adeneo Apr 21 '15 at 06:37
  • 1
    He asked for something and accepted something else. – Yellen Apr 21 '15 at 06:38
2

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(" "));
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
  • 1
    This puts the interpunction in the wrong spot: `"sihT si ,nuf .yllufepoh"`. Also that code snippet contains no jquery? – Jorg Apr 21 '15 at 06:16
  • This doesn't return "sihT si nuf, yllufepoh." – Yellen Apr 21 '15 at 06:28
  • Keep in mind that [`.split('').reverse().join('')` is not a good way to reverse strings in JavaScript](http://stackoverflow.com/a/16776621/96656). – Mathias Bynens Apr 21 '15 at 09:49
0

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;
}
V. Sambor
  • 12,361
  • 6
  • 46
  • 65
0

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))
-1

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);
bilalmohib
  • 280
  • 3
  • 16