简体   繁体   中英

Reverse letters of a word in a sentence

If there is a sentence like "HI my name is jack", how can I change it to "ih ym eman si kcaj" ?

The order is the same but the letters are reversed. it must be a function.

  var sentence = "HI my name is jack";

function reverser(){
var reversed = sentence.split().reverse().join();
document.write(reversed);
}

You could try it like this:

function reverser(inputSentence){
    var words = inputSentence.split(" "); // Split the sentence into words
    var output = new Array(); // Initiate the output
    words.forEach(function(word) { // For each word
        output.push(word.split("").reverse().join("")); // Reverse the word and add it to the output
    });
    return output.join(" "); // Join output to string and return it
}

Working Fiddle: http://jsfiddle.net/fRj4B/1

You need to split the entire sentence into words, iterate through the list of words, and reverse each word individually. Then, you need to join the entire thing back together to get the final sentence.

function reverse(sentence) {
    var reversed = [];
    sentence.split(' ').forEach(function (word) {
        reversed.push(word.split('').reverse().join(''));
    });
    return reversed.join(' ');
}
sentence.split(' ').map(function(str) { return str.split("").reverse().join(""); }).join(' ');
var sentance = "HI my name is jack";
alert(sentance.split("").reverse().join("").split(" ").reverse().join(" "));

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