在 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 生日开业蛋糕祝福语简短