Reverse word starting with particular characters - JavaScript

We need to write a JavaScript function that takes a sentence string and a character, then reverses all words starting with that specific character.

For example, if we have the string:

const str = 'hello world, how are you';

And we want to reverse words starting with 'h', the output should be:

const output = 'olleh world, woh are you';

Notice that "hello" becomes "olleh" and "how" becomes "woh" because both start with 'h'.

Solution

We'll split the string into words, check each word's first character, and reverse those that match our target character:

const str = 'hello world, how are you';

const reverseStartingWith = (str, char) => {
    const strArr = str.split(' ');
    return strArr.reduce((acc, val) => {
        if(val[0] !== char){
            acc.push(val);
            return acc;
        }
        acc.push(val.split('').reverse().join(''));
        return acc;
    }, []).join(' ');
};

console.log(reverseStartingWith(str, 'h'));
olleh world, woh are you

How It Works

The function follows these steps:

  1. Split: str.split(' ') converts the string into an array of words
  2. Check: val[0] !== char compares the first character of each word
  3. Reverse: val.split('').reverse().join('') reverses matching words by splitting into characters, reversing the array, and joining back
  4. Combine: join(' ') reconstructs the sentence with spaces

Alternative Approach Using Map

Here's a cleaner version using map():

const reverseStartingWithMap = (str, char) => {
    return str.split(' ').map(word => {
        return word[0] === char 
            ? word.split('').reverse().join('') 
            : word;
    }).join(' ');
};

console.log(reverseStartingWithMap('hello world, how are you', 'h'));
console.log(reverseStartingWithMap('apple banana cherry', 'a'));
olleh world, woh are you
elppa banana cherry

Handling Edge Cases

Let's make the function more robust by handling case sensitivity and punctuation:

const reverseStartingWithAdvanced = (str, char) => {
    return str.split(' ').map(word => {
        // Handle case-insensitive matching
        if(word.toLowerCase()[0] === char.toLowerCase()) {
            return word.split('').reverse().join('');
        }
        return word;
    }).join(' ');
};

console.log(reverseStartingWithAdvanced('Hello world, How are You', 'h'));
olleH world, woH are You

Conclusion

This function effectively reverses words starting with a specific character using array methods. The map() approach provides cleaner, more readable code than reduce() for this use case.

Updated on: 2026-03-15T23:18:59+05:30

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements