简体   繁体   中英

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.

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"

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.

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)

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;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM