我们需要编写一个 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