簡體   English   中英

JavaScript:如何在保持單詞、空格和標點符號的原始順序的同時反轉每個單詞中的字母?

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

我的方法:

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


}

例如, This IS a word-teSt,yo! 應該變成sihT SI a dorw-tSet,oy!. 我的代碼不適用於以下內容:

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

您只能匹配字母和反向匹配組。

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

這是一個簡單的解決方案,假設您想要反轉字符串,而不僅僅是向后排列單詞

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

var text = "Hey this is t3xt!";

console.log(backwards(text));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM