Reverse words in array string matching punctuation in Javascript - Stack Overflow

How do I reverse the words in this string including the punctuation? String.prototype.reverse = functio

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

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."
Share Improve this question edited Apr 21, 2015 at 6:22 thefourtheye 240k53 gold badges466 silver badges501 bronze badges asked Apr 21, 2015 at 6:03 whitehat1167whitehat1167 411 silver badge4 bronze badges 2
  • Why it is not .yllufepoh? – thefourtheye Commented Apr 21, 2015 at 6:26
  • Keep in mind that .split('').reverse().join('') is not a good way to reverse strings in JavaScript. – Mathias Bynens Commented Apr 21, 2015 at 9:49
Add a ment  | 

5 Answers 5

Reset to default 4

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 ma one space as it gets the ma and the space in one boundary and swaps them. If the ma needs to stay in the same spot, split on spaces as well, and change the regex to /(\b|\s)/g

Simply reversing the string wont give the solution.

  1. Get each word.
  2. Reverse It
  3. Again rejoin

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

You can imagine that you receive a stream of letters and you have to construct words based on some separators (like: spaces, mas, dashes .etc).

While reading each character you keep constructing the word in reverse.

When you hit any separator you finished the word.

Now you just add it to the result and append the separator (this way the separators will not be put at the beginning of the word, but at the end).

Here is an example:

const inputString = "HELLO, Wele to Google's meeting. My name is Jean-Piere... Bye";
console.log('Normal words: ', inputString);

const result = reverseWords(inputString);
console.log('Words reversed: ', result);

function reverseWords(str='', separators=' ,.-') {
    let result = '';
    let word = '';

    for (const char of str) {
        if (separators.includes(char)) {
            result += word + char;
            word = '';
        } else {
            word = char + word;
        }
    }
    
    // Adds last remaining word, if there is no separator at the end. 
    result += word;

    return result;
}

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

function reverseWords(str){
   const tempArr= str.split(" ")
   let reversedTempArr=''
   for(let i=0; i<tempArr.length;i++){
     let tempStr=''
     for(let j=tempArr[i].length-1;j>=0;j--){
       tempStr += tempArr[i][j]
     }
     reversedTempArr += tempStr+ " "
   }
   return reversedTempArr
}

console.log(reverseWords(str))

You can reverse each word in a string in squence by splitting that word in to an array of words and then reversing each word and storing it in a new array and then joining that array as shown below.

//1) Reverse words
function reverseWords(str) {
    // Go for it
    let reversed;
    let newArray=[];
    reversed = str.split(" ");
    for(var i = 0;i<reversed.length; i++)
    {
        newArray.push(reversed[i].split("").reverse().join(""));     
    }
    return newArray.join(" ");
}
let reversedString = reverseWords("This is fun, hopefully.");
console.log("This is the reversed string : ",reversedString);

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

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

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

关注微信