Reverse word starting with particular characters - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.


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){
         return acc;
      return acc;
   }, []).join(' ');
console.log(reverseStartingWith(str, 'h'));


Following is the output in the console −

olleh world, woh are you
Updated on 16-Sep-2020 09:52:22