参考答案:
在JavaScript中,我们可以通过多种方式实现清除字符串前后空格的功能。
以下是几种常见的实现方法:
1function trim(str) { 2 return str.trim(); 3} 4 5// 示例 6console.log(trim(' hello world ')); // 输出: "hello world"
1function trim(str) { 2 return str.replace(/^\s+|\s+$/g, ''); 3} 4 5// 示例 6console.log(trim(' hello world ')); // 输出: "hello world"
1function trim(str) { 2 let start = 0; 3 let end = str.length - 1; 4 5 // 找到前面第一个非空格字符的位置 6 while (start <= end && str[start] === ' ') { 7 start++; 8 } 9 10 // 找到后面第一个非空格字符的位置 11 while (end >= start && str[end] === ' ') { 12 end--; 13 } 14 15 // 返回去除空格后的子字符串 16 return str.substring(start, end + 1); 17} 18 19// 示例 20console.log(trim(' hello world ')); // 输出: "hello world"
1function trim(str) { 2 if (String.prototype.trim) { 3 return str.trim(); 4 } 5 return str.replace(/^\s+|\s+$/g, ''); 6}
最近更新时间:2025-07-16
题库维护不易,您的支持就是我们最大的动力!