Xinyi Li
Xinyi Li

Reputation: 133

How to reverse characters in words of a string, but keep word order?

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?

Upvotes: 5

Views: 56302

Answers (20)

aswininayak
aswininayak

Reputation: 973

let msg = "Welcome to New Jersey";

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

console.log(reverseMsg);

Upvotes: 0

pradeepks
pradeepks

Reputation: 51

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

Upvotes: -1

Akshay Bhatt
Akshay Bhatt

Reputation: 1

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

console.log(b)
 

Upvotes: -1

Manu Panduu
Manu Panduu

Reputation: 431

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)

Upvotes: 0

Shahid
Shahid

Reputation: 23

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

Upvotes: 0

Tawseef Bhat
Tawseef Bhat

Reputation: 460

let reverseOfWords = (words) =>{
  _words = words.split(" ").map(word => word.split('').reverse().join(""))
   console.log("reverse of words ", _words.join(' '))

}
reverseofWords("hello how are you ")

Upvotes: 0

Tawseef Bhat
Tawseef Bhat

Reputation: 460

reverseStringBywords = (str) =>{
  let rev = ""
  str.split(" ").forEach(s =>{ 
      rev = rev + s.split("").reverse().join("") + " " 
  })
  return  rev
}
console.log("reverseStringBywords ", reverseByWord("JavaScript is awesome"));

Upvotes: 0

Bhesaniya Rutesh
Bhesaniya Rutesh

Reputation: 1

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

Upvotes: 0

Soumya prakash Ojha
Soumya prakash Ojha

Reputation: 1

function reverse(str) {
    var rev = str.split("").map(word => word.split("").reverse().join("")).join(" ")
    return rev
}

console.log(reverse("soumya prakash")); // aymuos hsakarp

Upvotes: 0

Wesley Matteus
Wesley Matteus

Reputation: 3

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

Upvotes: 0

Sukshith S
Sukshith S

Reputation: 501

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

Upvotes: 0

Mukesh Mahajan
Mukesh Mahajan

Reputation: 1

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

Upvotes: 0

Vivekanand Panda
Vivekanand Panda

Reputation: 867

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

Upvotes: 1

bilalmohib
bilalmohib

Reputation: 288

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

Upvotes: 0

eroak
eroak

Reputation: 1045

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

Upvotes: 0

Ashish Devade
Ashish Devade

Reputation: 37

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

Upvotes: 1

Kunal Jain
Kunal Jain

Reputation: 61

This function should work for you:

function myFunction(string) {
    return string.split("").reverse().join("").split(" ").reverse().join(" ")
};

Upvotes: 11

Anurag Singh Bisht
Anurag Singh Bisht

Reputation: 2753

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

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68363

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

Upvotes: 6

Azad
Azad

Reputation: 5264

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

Upvotes: 6

Related Questions