javascript - How to reverse a string in place without reversing the punctuation? - Stack Overflow

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745622420a4636600.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信