简体   繁体   中英

JavaScript: How to reverse letters in each word while maintaining the original order of words, spaces and punctuation?

My Apporoach:

function wordReverse (str) {

if(str===""){
    return str;
}

punctuationMarksArray = [];
punctuationMarks = /[\-.,;"!_?\\ " "']/g;
punctuationMarksArray = str.match(punctuationMarks);
//now replace punctuation marks with an identifier
str = str.replace(punctuationMarks, "+0+");
//now split the string on the identifier
splitStringArray= str.split("+0+");
//now reverse all words within splitStringArray
splitStringArrayReversed=[];

for(i=0; i<splitStringArray.length; i++){
    reversedString= splitStringArray[i].split("").reverse().join("");
    splitStringArrayReversed.push(reversedString);
}
//now I got two arrays that I need to combine
//punctuationMarksArray and
//splitStringArrayReversed
wynikArray=[];
for(i=0; i<punctuationMarksArray.length; i++){
    wynikArray.push(splitStringArrayReversed[i]);
    wynikArray.push(punctuationMarksArray[i]);
}

return wynikArray.join("");


}

For example, This IS a word-teSt,yo! should turn into sihT SI a dorw-tSet,oy!. My code does not work on following:

wordReverse("You have reached the end of your free-trial membership at www.BenjaminFranklinQuotes.com! -BF");

You could match only letters and reverse matched groups.

 function reverse(string) { return string.replace(/[az]+/gi, function (s) { return s.split('').reverse().join(''); }); } console.log(reverse('This IS a word-teSt,yo!'));

Here's a simple solution assuming you want the string reversed, not just arrange the words backwards

function backwards(str) {
    return str.split("").reverse().join("");
}

var text = "Hey this is t3xt!";

console.log(backwards(text));

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