admin管理员组

文章数量:1434908

I am trying to reverse the words in a string without any effect on punctuation.
This is my current code:

function reverse(str) {
    str = str.split("").reverse().join("");
    str = str.split(" ").reverse().join(" ");
    console.log(str)
}; 

reverse("This is fun, hopefully.")

The result of the above function is sihT si ,nuf .yllufepoh
while I am trying to to get it like sihT si nuf, yllufepoh.

I am trying to reverse the words in a string without any effect on punctuation.
This is my current code:

function reverse(str) {
    str = str.split("").reverse().join("");
    str = str.split(" ").reverse().join(" ");
    console.log(str)
}; 

reverse("This is fun, hopefully.")

The result of the above function is sihT si ,nuf .yllufepoh
while I am trying to to get it like sihT si nuf, yllufepoh.

Share Improve this question edited Dec 10, 2015 at 1:13 Stephen P 14.8k2 gold badges48 silver badges70 bronze badges asked Dec 10, 2015 at 0:32 M Sohaib KhanM Sohaib Khan 1482 silver badges11 bronze badges 8
  • 1 You cannot reverse a string keeping punctuation characters in place. But you can reverse every word with keeping punctuation in place. Change your question to more clearly express your intentions. – zerkms Commented Dec 10, 2015 at 0:34
  • 4 Unclear what this should do. What is the expected output of your example? – Thilo Commented Dec 10, 2015 at 0:34
  • The result of above function is (sihT si ,nuf .yllufepoh). While i am trying to to get it like this(sihT si nuf, yllufepoh.) – M Sohaib Khan Commented Dec 10, 2015 at 0:36
  • What's the error? Please be more specific in both the error you are facing, and also provide the expected result. – k0pernikus Commented Dec 10, 2015 at 0:37
  • 2 So you're not trying to reverse the string, you are trying to reverse each word in the string. – Stephen P Commented Dec 10, 2015 at 0:38
 |  Show 3 more ments

3 Answers 3

Reset to default 5

Another approach is to replace all sequences of letters with their reversed forms using replace and a regular expression, e.g.

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

document.write(reverseWords("This is fun, hopefully.")); // sihT si nuf, yllufepoh. 

If you wish to include numbers as word characters (w.g. W3C), then the regular expression should be:

/\w+/g

Split the sentence on word boundaries, which doesn't consume any of the string,
then split each word into its letters (non-spaces with \S) using a lookahead ?= so those aren't consumed.
Reverse the array of the letters, then rejoin them with no separator .join("")
and finally rejoin the sentence, again with no separator because the spaces between the words were retained when originally splitting on word boundaries.

var sentence = "This is fun, hopefully.";
sentence.split(/\b/)
        .map(w => w.split(/(?=\S)/)
                   .reverse()
                   .join("") )
    .join("");

Doing this in Chrome's javascript console produced the output:
"sihT si nuf, yllufepoh."

Note this doesn't correctly handle a run of punctuation. For example hopefully!? would bee yllufepoh?!, reversing the punctuation too.

You can do better with Regular Expressions, but this is a simple solution that I just wrote.

function reverse(str){
    var out = '';
    var word = '';
    for (var i=0;i<str.length;i++) {
        // your punctuation characters
        if (',.!? '.indexOf(str[i]) == -1) word += str[i];
        else {
            out += word.split('').reverse().join('');
            out += str[i];
            word = '';
        }
    }
    return out;
}; 

console.log(reverse("This is fun, hopefully."));

本文标签: javascriptHow to reverse a string in place without reversing the punctuationStack Overflow