JavaScript 去除字符串末尾空格:高效实现与代码示例
使用字符串的 'trim()' 方法来去掉字符串两端的空格,然后再判断最后一位是否是空格,如果是,则使用字符串的 'slice()' 方法去掉最后一位。
代码示例:
function removeLastSpace(str) {
str = str.trim(); // 去掉两端空格
if (str.charAt(str.length - 1) === ' ') { // 判断最后一位是否是空格
str = str.slice(0, -1); // 去掉最后一位空格
}
return str;
}
// 测试
console.log(removeLastSpace('hello world ')); // 'hello world'
console.log(removeLastSpace(' hello world ')); // 'hello world'
console.log(removeLastSpace('hello world')); // 'hello world'
原文地址: https://www.cveoy.top/t/topic/loTy 著作权归作者所有。请勿转载和采集!