从特定字符开始反转单词 - JavaScript
我们需要编写一个 JavaScript 函数,该函数输入一个句子字符串和一个字符,并且该函数应反转字符串中所有以该特定字符开头的单词。
比如:如果字符串为 -
const str = 'hello world, how are you';
以特定字符 'h' 开头 -
那么输出字符串应为 -
const output = 'olleh world, woh are you';
这意味着,我们已经反转了以 “h” 开头的单词,即 Hello 和 How。
示例
以下是代码 -
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'));输出
以下是控制台中的输出 -
olleh world, woh are you
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP