以特定字符开头的反向单词-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
热门推荐
10 老人掉牙祝福语简短语
11 描写周末的祝福语简短
12 对离岗同事祝福语简短
13 姥爷生日诗句祝福语简短
14 儿媳买车妈妈祝福语简短
15 喜得新房文案祝福语简短
16 送去考试祝福语大全简短
17 周日徒步祝福语大全简短
18 开店大吉文案祝福语简短