Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wrote a code to reverse the word order in a sentence. The test sentence was in quotation marks and I need to have quotation marks in my solution but can't seem to add it in properly....

ex.
Test: "Go to the coffeeshop"

my code returns this: coffeeshop the to Go

But it needs to return this: "coffeeshop the to Go"

What I have tried:

Hi! I wrote a code for reversing word order in a sentence (without using the reverse method) and got this:

JavaScript
function reverseSent(sentence){
  var result = " ";
  var splitStr = sentence.split(" ");

  for (var i = splitStr.length - 1; i >= 0; i--){
    result += splitStr[i] + " ";
    var words = result;
  }
  return words;
}

-the order is right, but I'm missing the quotation marks at the beginning and end of the sentence. How can I add them in?
Posted
Updated 26-Mar-17 14:33pm
v2
Comments
Bryian Tan 26-Mar-17 15:41pm    
Can you cheat? return '"' + words + '"'; :)
Member 13085581 26-Mar-17 19:40pm    
I tried but I get a space at the beginning and the end in the word and the quotation mark :/
so my return would be: " coffeeshop the to Go "
and I need it to be: "coffeeshop the to Go"
Bryian Tan 26-Mar-17 20:09pm    
Well, that can be arrange :)
function reverseSent(sentence){
  var result = "";
  var splitStr = sentence.split(" ");

  for (var i = splitStr.length - 1; i >= 0; i--){
  
   if (i ==splitStr.length - 1) {
    	  result += "";
    }
    else {
    	result += " ";
    }
  
    result += splitStr[i];// + " ";
    var words = result;
  }
  return '"' + words + '"';
}
Bryian Tan 26-Mar-17 20:12pm    
by the way, hod did you pass in the "coffeeshop the to Go" into the function?

like this --> reverseSent("\"coffeeshop the to Go\""); ?
Member 13085581 27-Mar-17 0:18am    
yeah! This helped a lot! Thank you!

1 solution

JavaScript
function reverseSent(sentence){
  return sentence.split(/\b/).reverse().join('')
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900