仅反转奇数长度的单词 - JavaScript
我们需要编写一个 JavaScript 函数,该函数接受一个字符串,并反转字符串中长度为奇数的单词。
如果一个子串的两端都包含两个空格,或存在于末端或开头且其前后均为空格,则字符串中的任何子串就有资格成为单词。
假设我们的字符串如下所示 −
const str = 'hello beautiful people';
奇数长度的单词有 −
hello beautiful
范例
让我们编写该函数的代码。
const str = 'hello beautiful people';
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 lufituaeb people
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP