Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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
Advertisements
