在 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
热门推荐
5 小托班祝福语简短
10 心理考试祝福语结婚简短
11 女儿成年祝福语简短霸气
12 过年祝福语闺蜜简短
13 开工红包祝福语毕业简短
14 女神节祝福语简短创意
15 冬至宾馆祝福语简短独特
16 小年对儿子祝福语简短
17 同事孩子上学祝福语简短
18 最佳元旦祝福语简短学校