我们需要编写一个JavaScript函数,该函数接受一个字符串并反转字符串中包含奇数个字符的单词。
如果字符串中的任何子字符串在两端都被两个空格封装,或者在结尾或开头出现并且在其后或之前带有空格,则该子字符串都可以视为单词。
为此的代码将是-
const str = 'hello world, how are you';
const idOdd = str => str.length % 2 === 1;
const reverseOddWords = (str = '') => {
const strArr = str.split(' ');
return strArr.reduce((acc, val) => {
if(idOdd(val)){
acc.push(val.split('').reverse().join(''));
return acc;
};
acc.push(val);
return acc;
}, []).join(' ');
};
console.log(reverseOddWords(str));输出结果
以下是控制台上的输出-
olleh world, woh era uoy