這是lgzx公司的一道面試題,要求給js的String添加一個方法,去除字符串兩邊的空白字符(包括空格、製錶符、換頁符等)
String.prototype.trim = function() {
//return this.replace(/[(^\s+)(\s+$)]/g,"");//會把字符串中間的空白符也去掉
//return this.replace(/^\s+|\s+$/g,""); //
return this.replace(/^\s+/g,"").replace(/\s+$/g,"");
}
JQuery1.4.2 Mootools 使用
function trim1(str){
return str.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g, '');
}
jQuery1.4.3 Prototype 使用,该方式去掉g以稍稍提高性能 在小规模的处理字符串时性能较好
function trim2(str){
return str.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');
}
Steven Levithan 在进行性能测试后提出了在JS中执行速度最快的裁剪字符串方式,在处理长字符串时性能较好
function trim3(str){
str = str.replace(/^(\s|\u00A0)+/,'');
for(var i=str.length-1; i>=0; i--){
if(/\S/.test(str.charAt(i))){
str = str.substring(0, i+1);
break;
}
}
return str;
}
PS: ECMA-262(V5) 中给String添加了原生的trim方法(15.5.4.20)。此外Molliza Gecko 1.9.1引擎中还给String添加了trimLeft ,trimRight 方法。