Reverse word starting with particular characters - JavaScript


We are required to write a JavaScript function that takes in a sentence string and a character and the function should reverse all the words in the string starting with that particular character.

For example: If the string is −

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

Starting with a particular character ‘h’ −

Then the output string should be −

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

That means, we have reversed the words starting with “h” i.e. Hello and How.

Example

Following is the code −

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'));

Output

Following is the output in the console −

olleh world, woh are you

Updated on: 16-Sep-2020

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements