"```javascript /**
- 将字符串从 "hello-world-js" 转换为 "js-world-hello"
- @param {string} str - 需要转换的字符串
- @returns {string} - 转换后的字符串 */ function convertString(str) { // 使用split方法将字符串按照"-"分割为数组 let arr = str.split("-"); // 使用reverse方法将数组元素反转 arr.reverse(); // 使用join方法将数组元素连接为字符串,使用"-"作为连接符 let result = arr.join("-"); // 返回转换后的字符串 return result; }
// 调用convertString方法并打印结果 console.log(convertString("hello-world-js")); // 输出: "js-world-hello"
在上述代码中,我们定义了一个名为`convertString`的函数,它接受一个字符串参数`str`,并返回转换后的字符串。
首先,我们使用`split`方法将输入的字符串按照\"-\"分割为数组。然后,我们使用`reverse`方法将数组元素反转,使得\"hello\"变为\"js\",\"world\"变为\"world\",\"js\"变为\"hello\"。最后,我们使用`join`方法将数组元素连接为字符串,并使用\"-\"作为连接符。
最后,我们调用`convertString`方法并将\"hello-world-js\"作为参数传入,并通过`console.log`打印结果。控制台将输出\"js-world-hello\"作为转换后的字符串。
这个方法可以帮助我们将\"hello-world-js\"这样的字符串转换为\"js-world-hello\",通过对字符串的分割、反转和连接操作实现了字符串的转换。"