Reverse words in array string matching punctuation in Javascript

前端 未结 3 1996
感动是毒
感动是毒 2021-01-22 03:48

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

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


        
相关标签:
3条回答
  • 2021-01-22 04:17

    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

    0 讨论(0)
  • 2021-01-22 04:19

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

    0 讨论(0)
  • 2021-01-22 04:19

    You can imagine that you receive a stream of letters and you have to construct words based on some separators (like: spaces, commas, 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, Welcome 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;
    }

    0 讨论(0)
提交回复
热议问题