问答题587/1629实现下面的 reverseWord 方法

1/** 2 * @file 反转句子 3 * 4 * 同时满足以下条件:1、去除首尾空格,2、单词间隔中多个空格变成一个; 5 * 注意console示例运行结果 6 */ 7 8function reverseWord(str: string) { 9 // 补全此处代码 10 throw new Error('功能待实现'); 11} 12 13console.log(reverseWord('the sky is blue')); // blue is sky the 14// 去除首尾空格 15console.log(reverseWord(" hello world ")); // world hello 16// 单词间隔中多个空格变成一个 17console.log(reverseWord("a good example")); // example good a 18 19export default {}
难度:
2023-03-12 创建

参考答案:

1/** 2 * @file 反转句子 3 * 4 * 同时满足以下条件:1、去除首尾空格,2、单词间隔中多个空格变成一个; 5 * 注意console示例运行结果 6 */ 7 8function reverseWord(str: string):string { 9 // 参考答案 10 return (<string[]>str.match(/\S+/g)).reverse().join(" "); 11} 12 13console.log(reverseWord('the sky is blue')); // blue is sky the 14// 去除首尾空格 15console.log(reverseWord(" hello world ")); // world hello 16// 单词间隔中多个空格变成一个 17console.log(reverseWord("a good example")); // example good a 18 19export default {}

最近更新时间:2024-08-10

赞赏支持

题库维护不易,您的支持就是我们最大的动力!