151. Flip the word in the string

Answer:

  1. String flipping is completed by cutting strings into arrays by Spaces, flipping arrays and merging them into strings.
  2. Note the following two points:
    • The original string starts and ends with Spaces.
    • Input can have more than one space, and output can have only one space.
/ * * *@param {string} s
 * @return {string}* /
var reverseWords = function (s) {
  return s
    .trim() // Remove the leading and trailing Spaces
    .split(/\s+/) // Cut multiple Spaces into arrays
    .reverse() // Invert the array
    .join(' '); // Separate arrays with Spaces and merge them into strings
};
Copy the code