How to reverse words in a string instead of reversing the whole string?
Asked Answered
L

20

5
function reverseInPlace(str) {
    var words = [];
    words = str.split("\s+");
    var result = "";
    for (var i = 0; i < words.length; i++) {
        return result += words[i].split('').reverse().join('');
    }
}
console.log(reverseInPlace("abd fhe kdj"))

What I expect is dba ehf jdk, while what I'm getting here is jdk fhe dba. What's the problem?

Lamoreaux answered 19/3, 2018 at 10:26 Comment(5)
return inside a multi-iteration for-loop ?!Dizzy
I don't understand,,,can't I do this?Lamoreaux
As an aside: "In place" doesn't mean what you seem to think it should. An "in place" operation would act like: s = 'abd fhe kdj'; reverseInPlace(s); console.log(s).Heikeheil
"abd fhe kdj".split( " " ).map( s => s.split("").reverse().join( "" ) ).join( " " )Kaiulani
if u return a function inside a loop. loop will not run entirely it will itereate only once.Duyne
T
6

you need to split the string by space

function reverseInPlace(str) {
  var words = [];
  words = str.match(/\S+/g);
  var result = "";
  for (var i = 0; i < words.length; i++) {
     result += words[i].split('').reverse().join('') + " ";
  }
  return result
}
console.log(reverseInPlace("abd fhe kdj"))
Tansy answered 19/3, 2018 at 10:31 Comment(3)
Thanks! But can you tell me why "split" does not work when I try to split the string into array on the third line?Lamoreaux
@XinyiLi if you want to split the string using regex you cannot double quotes you can use like this str.split(/\s+/);Tansy
yup absolutely!Lamoreaux
G
10

This function should work for you:

function myFunction(string) {
    return string.split("").reverse().join("").split(" ").reverse().join(" ")
};
Gratifying answered 19/3, 2018 at 10:42 Comment(0)
T
6

you need to split the string by space

function reverseInPlace(str) {
  var words = [];
  words = str.match(/\S+/g);
  var result = "";
  for (var i = 0; i < words.length; i++) {
     result += words[i].split('').reverse().join('') + " ";
  }
  return result
}
console.log(reverseInPlace("abd fhe kdj"))
Tansy answered 19/3, 2018 at 10:31 Comment(3)
Thanks! But can you tell me why "split" does not work when I try to split the string into array on the third line?Lamoreaux
@XinyiLi if you want to split the string using regex you cannot double quotes you can use like this str.split(/\s+/);Tansy
yup absolutely!Lamoreaux
K
5

Split the string into words first before reversing the individual words

var input = "abd fhe kdj";
var output = input.split( " " ).map(  //split into words and iterate via map
     s => s.split("").reverse().join( "" )  //split individual words into characters and then reverse the array of character and join it back
).join( " " ); //join the individual words
Kaiulani answered 19/3, 2018 at 10:33 Comment(0)
E
1

If you are looking like this o/p : "Javascript is Best" => "Best is Javascript"

Then can be done by simple logic

//sample string
     let str1 = "Javascript is Best";
//breaking into array
     let str1WordArr = str1.split(" ");
//temp array to hold the reverse string      
      let reverseWord=[];
//can iterate the loop backward      
     for(let i=(str1WordArr.length)-1;i>=0;i--)
     {
//pushing the reverse of words into new array
          reverseWord.push(str1WordArr[i]); 
     }
//join the words array 
      console.log(reverseWord.join(" ")); //Best is Javascript
Essie answered 2/5, 2020 at 10:6 Comment(0)
I
1

const reverseWordIntoString = str => str.split(" ").map(word => word.split("").reverse().join('')).join(" ")

const longString = "My name is Vivekanand Panda";
const sentence = "I love to code";


const output = {
  [longString]: reverseWordIntoString(longString),
  [sentence]: reverseWordIntoString(sentence)
}

console.log(output);
Isochromatic answered 8/9, 2021 at 10:39 Comment(0)
N
0

You can make use of split and map function to create the reverse words.

You need to first split the sentence using space and then you can just reverse each word and join the reversed words again.

function reverseWord (sentence) {
  return sentence.split(' ').map(function(word) {
    return word.split('').reverse().join('');
  }).join(' ');
}

console.log(reverseWord("abd fhe kdj"));
Neely answered 19/3, 2018 at 10:36 Comment(0)
T
0

This solution preserves the whitespaces characters space , the tab \t, the new line \n and the carriage return \r) and preserves their order too (not reversed) :

const sentence = "abd\t fhe kdj";

function reverseWords(sentence) {
    return sentence
        .split(/(\s+)/)
        .map(word => /^\s+$/.test(word) ? word : word.split('').reverse().join(''))
        .join('');
}

console.log(reverseWords(sentence));
Talkathon answered 2/5, 2020 at 10:45 Comment(0)
I
0
If you want to reverse a string by word:
Example: 'Welcome to JavaScript' to 'JavaScript to Welcome'

You can also do something like:
var str = 'Welcome to JavaScript'
function reverseByWord(s){
  return s.split(" ").reverse().join(" ");
}

// Note: There is space in split() and Join() method

reverseByWord(str)
// output will be - JavaScript to Welcome
Inapprehensible answered 24/2, 2021 at 7:14 Comment(0)
W
0

You can easily achieve that by the following code

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 an example!");
console.log("This is the reversed string : ",reversedString);
Wafd answered 15/7, 2021 at 6:54 Comment(0)
F
0

the only mistake is while doing split you can do something like:

function reverseInPlace(str) {
    var words = [];
    words = str.split(" ");
    console.log(words);
    var result = "";
    for (var i = 0; i < words.length; i++) {
         result += words[i].split('').reverse().join('') +" ";
    }
    return result
}
console.log(reverseInPlace("abd fhe kdj"))
Felony answered 21/7, 2022 at 7:50 Comment(0)
V
0
function reverse(str) {
    var rev = str.split("").map(word => word.split("").reverse().join("")).join(" ")
    return rev
}

console.log(reverse("soumya prakash")); // aymuos hsakarp
Vietnamese answered 12/9, 2022 at 7:23 Comment(1)
Please see this for help with formatting code in your answer.Jackjackadandy
C
0

let s = “getting good at coding needs a lot of practice”
let b = s.split(" ").reverse().join(" ")

console.log(b)
 
Charactery answered 17/11, 2022 at 5:51 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Neckline
P
0

-> Split the string into array of words str.split(" ") -> map the each word and split into each characters .map(word => word.split("") -> reverse the each word individually and join it

.map(word => word.split("").reverse().join("")

const str = "abd fhe kdj";

const reverseWord = str => {
  let reversed = "";
  reversed = str.split(" ").map(word => word.split("").reverse().join("")).join(" ")
  
  
  return reversed
}

console.log(reverseWord(str));
Phytophagous answered 9/12, 2022 at 5:46 Comment(0)
Q
0

For people looking into this problem now, think whether your application doesn't need to deal with punctuation marks (e.g. not moving punctuation marks around) or flipped hyphenated words (e.g. check-in should be ni-kcehc or kcehc-ni ?).

For example:

  • "ignorance is bliss?!" should really be "ecnarongi si !?ssilb" ?
  • "Merry-go-round" should be "dnuor-og-yrreM" or "yrreM-og-dnuor" ?

The following solution doesn't move punctuation marks and it doesn't flip hyphenated words:

/**
* 1. Split "non letters"
* 2. Reverse each piece
* 3. Join the pieces again, replacing them by " "
* 4. Split all characters
* 5. Replace " " by the original text char
*/

function reverseWords(text) {
    return text.split(/[^A-Za-zÀ-ÿ]/g)
        .map(w => w.split("").reverse().join(""))
        .join(" ")
        .split("")
        .map((char, i) => char === " " ? text[i] : char)
        .join("")
}
Quemoy answered 11/5, 2023 at 17:17 Comment(0)
S
0

function reverseInPlace(str) {
  var words = [];
  words = str.match(/\S+/g);
  var result = "";
  for (var i = 0; i < words.length; i++) {
     result += words[i].split('').reverse().join('') + " ";
  }
  return result
}
console.log(reverseInPlace("abd fhe kdj"))
Shift answered 29/5, 2023 at 6:53 Comment(2)
Hi, you added no explanations. "Brevity is acceptable, but fuller explanations are better", as suggested in the help page. Please read how to answerMogerly
Please add some explanation.Deas
G
0
reverseStringBywords = (str) =>{
  let rev = ""
  str.split(" ").forEach(s =>{ 
      rev = rev + s.split("").reverse().join("") + " " 
  })
  return  rev
}
console.log("reverseStringBywords ", reverseByWord("JavaScript is awesome"));
Gow answered 19/8, 2023 at 7:12 Comment(0)
G
0
let reverseOfWords = (words) =>{
  _words = words.split(" ").map(word => word.split('').reverse().join(""))
   console.log("reverse of words ", _words.join(' '))

}
reverseofWords("hello how are you ")
Gow answered 1/9, 2023 at 17:37 Comment(0)
I
0

Try this reverseString(). This can be use for both 'reverse the entire string' and 'reverse each word'.

function reverseString(string, separator) {
  return string.split(separator).reverse().join(separator);
}

const str = "See the magic of javaScript"

const reverseWholeString = reverseString(str, "");
console.log("Reverse the whole string ->", reverseWholeString);

const reverseEachWord = reverseString(reverseWholeString, " ");
console.log("Reverse each word ->", reverseEachWord);
Impresario answered 6/9, 2023 at 11:59 Comment(0)
C
0

without using build method, using for loop

const mainString = "this is test hey";
const splitedString = mainString.split(" ");
let string = "";
let word = "";
let result = "";
for (let i=0;i<splitedString.length;i++){
   word = splitedString[i];
   for(let j=0;j<word.length;j++){
       string = word[j] + string;
       if (word.length - 1 === j) {
           word = "";
          result = result + " " + string;
          string = ""
       }
   }
}
console.log(result)
Cayser answered 17/6 at 7:42 Comment(0)
F
0

let msg ="Welcome to New Jersey";

let reverseMsg = msg.split(" ").map(w => w.split("").reverse().join('')).join(' ');

console.log(reverseMsg);
Froggy answered 9/10 at 18:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.