写一个方法,将字符串中的单词倒转后输出,如:`my love` -> `ym evol`

function reverseWords(str) {
  // 1. Split the string into words
  const words = str.split(" ");

  // 2. Reverse each word
  const reversedWords = words.map(word => {
    return word.split("").reverse().join("");
  });

  // 3. Join the reversed words back into a string
  return reversedWords.join(" ");
}

// Example usage:
const inputString = "my love";
const reversedString = reverseWords(inputString);
console.log(reversedString); // Output: ym evol


// More concise version using chaining:
const reverseWordsConcise = (str) => str.split(" ").map(word => word.split("").reverse().join("")).join(" ");

console.log(reverseWordsConcise("hello world")); // Output: olleh dlrow


// Handling multiple spaces and edge cases (empty string, single word, leading/trailing spaces):
function reverseWordsRobust(str) {
  if (!str) return ""; // Handle empty string

  return str.trim() // Remove leading/trailing spaces
    .split(/\s+/) // Split by one or more spaces
    .map(word => word.split("").reverse().join(""))
    .join(" ");
}

console.log(reverseWordsRobust("  hello  world  ")); // Output: olleh dlrow
console.log(reverseWordsRobust(" single")); // Output: elgnis
console.log(reverseWordsRobust("")); // Output: ""


// Using a for loop for reversal (slightly more performant for very large words):

function reverseWordWithLoop(word) {
  let reversed = "";
  for (let i = word.length - 1; i >= 0; i--) {
    reversed += word[i];
  }
  return reversed;
}

function reverseWordsWithLoop(str) {
    if (!str) return "";

    return str.trim()
      .split(/\s+/)
      .map(word => reverseWordWithLoop(word))
      .join(" ");
}

console.log(reverseWordsWithLoop("hello world")); // Output: olleh dlrow



This provides several versions of the function:

  • reverseWords: Basic implementation.
  • reverseWordsConcise: A more concise version using method chaining.
  • reverseWordsRobust: Handles multiple spaces, leading/trailing spaces, and empty strings. This is generally the most robust solution.
  • reverseWordsWithLoop: Uses a for loop for character reversal within each word. This can be slightly more performant than using split("").reverse().join("") for very large words, though the difference is usually negligible.

Choose the version that best suits your needs and coding style. The robust version is recommended for most real-world applications. The for loop version might be preferred if performance is a critical concern and you're dealing with potentially very long words.

posted @   王铁柱6  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示