Aessandro
Aessandro

Reputation: 5761

JavaScript reverse the order of letters for each word in a string

I am trying to get around the following but no success:

var string = 'erehT era a tsav rebmun fo secruoser rof gninrael erom tpircsavaJ';

var x = string.split(' ');
for (i = 0; i <= x.length; i++) {
  var element = x[i];
}

element now represents each word inside the array. I now need to reverse not the order of the words but the order of each letter for each word.

Upvotes: 5

Views: 17793

Answers (5)

Penny Liu
Penny Liu

Reputation: 17428

JavaScript split with regular expression:

Note: ([\s,.]) The capturing group matches whitespace, commas, and periods.

const string = "oT eb ro ton ot eb, taht si a noitseuq.";

function reverseHelper(str) {
  return str.split(/([\s,.])/).
  map((item) => {
    return item.split``.reverse().join``;
  }).join``;
}

console.log(reverseHelper(string));

Upvotes: 0

Junu
Junu

Reputation: 49

You can do the following.

var string = "erehT era a tsav rebmun fo secruoser rof gninrael erom tpircsavaJ";

arrayX=string.split(" ");
arrayX.sort().reverse();
var arrayXX='';
arrayX.forEach(function(item){
items=item.split('').sort().reverse();
arrayXX=arrayXX+items.join('');
});
document.getElementById('demo').innerHTML=arrayXX;

Upvotes: 0

Mwiza
Mwiza

Reputation: 8961

You can do the following:

let stringToReverse = "tpircsavaJ";

stringToReverse.split("").reverse().join("").split(" ").reverse().join(" ")

//let keyword allows you declare variables in the new ECMAScript(JavaScript)

Upvotes: 0

Praveen Lobo
Praveen Lobo

Reputation: 7187

var string = "erehT era a tsav rebmun fo secruoser rof gninrael erom tpircsavaJ";
// you can split, reverse, join " " first and then "" too
string.split("").reverse().join("").split(" ").reverse().join(" ")

Output: "There are a vast number of resources for learning more Javascript"

Upvotes: 16

plalx
plalx

Reputation: 43718

You can do it like this using Array.prototype.map and Array.prototype.reverse.

var result = string.split(' ').map(function (item) {
    return item.split('').reverse().join('');
}).join(' ');

what's the map function doing there?

It traverses the array created by splitting the initial string and calls the function (item) we provided as argument for each elements. It then takes the return value of that function and push it in a new array. Finally it returns that new array, which in our example, contains the reversed words in order.

Upvotes: 8

Related Questions