iwfe / leetcode

3 stars 0 forks source link

151. Reverse Words in a String #6

Open Ge-yuan-jun opened 7 years ago

Ge-yuan-jun commented 7 years ago

Given an input string, reverse the string word by word.

For example, Given s = "the sky is blue", return "blue is sky the"

Ge-yuan-jun commented 7 years ago
/**
 * @param {string} str
 * @returns {string}
 */
var reverseWords = function(str) {
    return str.replace(/ +/ig,' ').replace(/^ /,'').split(' ').reverse().join(' ').replace(/ ?/,''); 
};