JavaScript:如何在保持单词,空格和标点符号的原始顺序的同时反转每个单词中的字母?

时间:2017-10-27 20:08:08

标签: javascript

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


}

例如,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");

2 个答案:

答案 0 :(得分:1)

您只能匹配字母和反向匹配的组。

function reverse(string) {
    return string.replace(/[a-z]+/gi, function (s) {
       return s.split('').reverse().join('');
    });
}

console.log(reverse('This IS a word-teSt,yo!'));

答案 1 :(得分:0)

这是一个简单的解决方案,假设您希望字符串被反转,而不仅仅是向后排列字词

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

var text = "Hey this is t3xt!";

console.log(backwards(text));