jquery去空格
去除字符串两端空格
使用 $.trim() 方法可以去除字符串两端的空格。这是jQuery提供的便捷方法,底层实现与原生JavaScript的String.prototype.trim()一致。
var str = " hello world ";
var trimmedStr = $.trim(str);
console.log(trimmedStr); // 输出 "hello world"
去除所有空格
如果需要去除字符串中的所有空格(包括中间的空格),可以使用正则表达式配合replace方法:
var str = " hello world ";
var noSpaceStr = str.replace(/\s+/g, '');
console.log(noSpaceStr); // 输出 "helloworld"
替换多个连续空格为单个空格
有时需要将多个连续空格替换为单个空格:
var str = "hello world";
var singleSpaceStr = str.replace(/\s+/g, ' ');
console.log(singleSpaceStr); // 输出 "hello world"
处理表单输入值
处理表单输入值时,通常需要先去除两端空格:
$('#myInput').val(function(i, val) {
return $.trim(val);
});
处理对象属性值
可以扩展jQuery方法批量处理对象属性值:
$.fn.trimValues = function() {
return this.each(function() {
var $el = $(this);
if ($el.is('input, textarea')) {
$el.val($.trim($el.val()));
} else {
$el.text($.trim($el.text()));
}
});
};
// 使用示例
$('.trim-me').trimValues();
性能考虑
对于大量字符串处理,原生JavaScript的trim方法性能更优:

var str = " text ";
var trimmed = str.trim();
现代浏览器都支持原生trim方法,jQuery的$.trim()实际上是对原生方法的封装,并提供了对旧浏览器的兼容支持。






