Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse words in array string matching punctuation in Javascript

How do I reverse the words in this string including the punctuation?

String.prototype.reverse = function () {
    return this.split('').reverse().join('');
}

var str = "This is fun, hopefully.";
str.reverse();

Currently I am getting this:

".yllufepoh ,nuf si sihT"

When I want to return this:

"sihT si nuf, yllufepoh."
like image 246
whitehat1167 Avatar asked May 31 '26 11:05

whitehat1167


1 Answers

You could reverse each word instead of the whole string, but you have to keep spaces, periods etc seperate, so a word boundary is needed

String.prototype.reverse = function () {
    return this.split(/\b/g).map(function(word) {
        return word.split('').reverse().join('');
    }).join('');
}

var str = "This is fun, hopefully.";

document.body.innerHTML = str.reverse();

Note that this moves the comma one space as it gets the comma and the space in one boundary and swaps them. If the comma needs to stay in the same spot, split on spaces as well, and change the regex to /(\b|\s)/g

like image 98
adeneo Avatar answered Jun 02 '26 23:06

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!