在 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