DEV Community

Cover image for String reversal in TypeScript: A step-by-step guid
Luqman Shaban
Luqman Shaban

Posted on

String reversal in TypeScript: A step-by-step guid

Introduction: In the ever-evolving world of data structures and algorithms (DSA), string manipulation is a fundamental skill every developer should master. In this article, we'll tackle the task of reversing the order of words in a string. This seemingly simple challenge can be a great exercise for both beginners and experienced programmers. We'll walk through a JavaScript solution step by step.

Step 1: Understand the Problem
Before we start coding, it's crucial to fully understand the problem statement. We're given an input string s, which contains words separated by spaces. Our goal is to reverse the order of these words while ensuring that there's only a single space between each word. It's also important to handle leading and trailing spaces.

Step 2: Plan Your Approach
To solve this problem, we'll break it down into smaller steps:

  1. Split the input string s into an array of words.
  2. Reverse the order of the words.
  3. Join the reversed words into a single string with a single space between each word.
  4. Remove any leading or trailing spaces.
  5. Return the reversed string.

Step 3: Code the Solution
Here's a JavaScript function that implements our plan:

function reverseWords(s) {
    const words = s.split(/\s+/);
    const reversedWords = words.reverse();
    return reversedWords.join(' ').trim();
}
Enter fullscreen mode Exit fullscreen mode

This code first splits the input string into an array of words using a regular expression to handle multiple spaces as word separators. Then, it reverses the order of words, joins them back into a single string with a single space separator, and trims any leading or trailing spaces.

Step 4: Test Your Solution
To ensure your code works as expected, it's crucial to test it with various inputs, including edge cases. For example:

console.log(reverseWords("  Hello   World!  ")); // Output: "World! Hello"
console.log(reverseWords("The quick brown   fox")); // 
Enter fullscreen mode Exit fullscreen mode

_**Output:**_ "fox brown quick The"

Conclusion: In this article, we've successfully solved the word reversal problem step by step using JavaScript. We handled various input scenarios, including leading/trailing spaces and multiple spaces between words. This exercise is a great example of how DSA concepts and problem-solving skills can be applied to real-world coding challenges.
Let's Connect

Happy coding!

Top comments (0)