在 JavaScript 中交换字符串中单词的首字母
问题
我们需要编写一个JavaScript函数,它接收一个包含两个单词的字符串。
我们的函数应该构造并返回一个新的字符串,其中单词的第一个字母相互交换。
示例
以下是代码-
const str = 'hello world';
const interchangeChars = (str = '') => {
const [first, second] = str.split(' ');
const fChar = first[0];
const sChar = second[0];
const newFirst = sChar + first.substring(1, first.length);
const newSecond = fChar + second.substring(1, second.length);
const newStr = newFirst + ' ' + newSecond;
return newStr;
};
console.log(interchangeChars(str));输出结果以下是控制台输出-
wello horld
热门推荐
10 美好的成语祝福语简短
11 幼儿祝福语押韵句子简短
12 带清的简短祝福语
13 团队海报祝福语简短英语
14 拥有爱的祝福语简短
15 夸赞老师祝福语搞笑简短
16 邻家生小孩祝福语简短
17 开店大吉文案祝福语简短
18 关于开车的祝福语简短