We are required to write a JavaScript function that takes in a string that might contain spaces. Our function should first split the string based on the spaces and then reverse and join and return the new string.
For example − If the input string is −
const str = 'this is a word';
Then the output should be −
const output = 'siht si a drow';
Example
const str = 'this is a word';
const reverseWords = (str = '') => {
const strArr = str.split(' ');
for(let i = 0; i < strArr.length; i++){
let el = strArr[i];
strArr[i] = el
.split('')
.reverse()
.join('');
};
return strArr.join(' ');
};
console.log(reverseWords(str));Output
And the output in the console will be −
siht si a drow