Open In App

Reverse Words Starting with Particular Characters using JavaScript

Last Updated : 08 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We need to create a JavaScript function that reverses the order of all words in a given sentence that begins with a specific character. JavaScript allows us to reverse the words in a sentence that start with specific letters.

Examples:

Input: 
str= "I like to cook delicious meals every day"

Character ch: "d"

Output:
"I like to cook suoiliced meals every yad"

Explanation:
In the input sentence, the word "delicious" starts with "d", so it gets reversed to "suoiliced". Similarly, the word "day" starts with "d", so it gets reversed to "yad". The rest of the words remain unchanged.

Algorithm:

  • Splitting the sentence : We start by splitting the input sentence into individual words. This creates an array where each element represents a word in the sentence.
  • Iterating through words : Next, we go through each word in the array one by one. This is typically done using a loop that goes from the first word to the last word in the array.
  • Checking for specified characters : For each word, we check if it starts with the specified characters. We can do this by using the ‘startsWith( )’ method available for strings in JavaScript.
  • Reversing words : If a word starts with the specified characters, we reverse it. To reverse a word, we split it into individual characters, reverse the order of those characters, and then join them back together into a single string.
  • Joining words back into a sentence : Finally, after we have processed all the words, we join them back together into a single sentence. This is done using the `join()` method available for arrays in JavaScript.

Example: To demonstrate reversing a word starting with particular character using JavaScript.

JavaScript
function reverseWordsStartingWith(sentence, characters) {
    let words = sentence
        .split(" ");
    for (let i = 0; i < words.length; i++) {
        // Check if the word starts 
        // with the specified characters
        if (words[i].startsWith(characters)) {
            // If it does, reverse the word
            words[i] = words[i]
                .split("")
                .reverse()
                .join("");
        }
    }
    // Join the words back into a sentence
    return words.join(" ");
}

console
    .log(reverseWordsStartingWith("I like to cook delicious meals every day", "d"));

Output
I like to cook suoiciled meals every yad

Time Complexity: O(n + m * k + l)

Auxiliary Space: O(m + n)

Using Array filter and Map method

  • The sentence is split into an array of words using split(” “).
  • The filter method is applied to select only the words that start with the specified characters.
  • For each selected word, the map() method is used to reverse the characters.
  • Finally, the modified words are joined back into a sentence using join(” “).

Example: To demonstrate reversing a word starting with a particular character using JavaScript array methods.

JavaScript
function revWrdSt(sentence, characters) {
    return sentence.split(" ")
        .map(word => word
            .startsWith(characters) ? word
                .split("")
                .reverse()
                .join("") : word)
        .join(" ");
}

console.log(revWrdSt(
    "I like to cook delicious meals every day", "d"));

Output
I like to cook suoiciled meals every yad

Time Complexity: O(n + m + k)

Auxiliary Space: O(n + m + k)

Using Iterative method

This approach employs a traditional iterative method to reverse words in a sentence that start with specific characters. Here are the key steps:

  • Splitting the Sentence: The input sentence is split into an array of words.
  • Iterating through Words: A loop iterates through each word in the array.
  • Checking Start Characters: For each word, it checks if it starts with the specified characters.
  • Reversing Selected Words: If a word starts with the specified characters, it reverses the word.
  • Reassembling Sentence: Finally, the modified words are joined back into a sentence.

Example: To demonstrate reversing word starting with particular character using the iterative method in JavaScript.

JavaScript
function revWrdSt(sentence, characters) {
    let words = sentence.split(" ");
    for (let i = 0; i < words.length; i++) {
        if (words[i].startsWith(characters)) {
            words[i] = words[i]
                .split("")
                .reverse()
                .join("");
        }
    }
    return words.join(" ");
}

console.log(revWrdSt("I like to cook delicious meals every day", "d"));

Output
I like to cook suoiciled meals every yad

Time Complexity: O(n + m + k)

Auxiliary Space: O(n + k)

Using Regular Expression

This approach utilizes JavaScript’s regular expressions to identify words starting with specific characters and then reverses those words. Here’s a breakdown of the steps involved:

  • Regular Expression Matching: A regular expression is constructed to match words starting with the specified characters.
  • Replacement with Reversed Words: The replace method is used with the regular expression to replace each matched word with its reversed form.
  • Reassembling Sentence: The modified sentence with reversed words is returned.

Example: To demonstrate reversing word starting with particular character using the regular expression in JavaScript.

JavaScript
function revWrdSt(sentence, characters) {
    return sentence
        .replace(new RegExp("\\b" + characters + "\\w+", "g"),
            match => match
                .split("")
                .reverse()
                .join(""));
}

console.log(revWrdSt(
    "I like to cook delicious meals every day", "d"));

Output
I like to cook suoiciled meals every yad

Time Complexity: O(n)

Auxiliary Space: O(n)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads