Javascript中各种trim的实现

http://www.cnblogs.com/snandy/archive/2011/02/26/1965866.html

Javascript中各种trim的实现

這是lgzx公司的一道面試題,要求給js的String添加一個方法,去除字符串兩邊的空白字符(包括空格、製錶符、換頁符等)

1

2

3

4

5

String.prototype.trim =function() {

//return this.replace(/[(^\s+)(\s+$)]/g,"");//會把字符串中間的空白符也去掉

//return this.replace(/^\s+|\s+$/g,""); //

returnthis.replace(/^\s+/g,"").replace(/\s+$/g,"");

}

JQuery1.4.2,Mootools 使用

1

2

3

functiontrim1(str){

returnstr.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g,'');

}

jQuery1.4.3,Prototype 使用,该方式去掉g以稍稍提高性能 在小规模的处理字符串时性能较好

1

2

3

functiontrim2(str){

returnstr.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');

}

Steven Levithan 在进行性能测试后提出了在JS中执行速度最快的裁剪字符串方式,在处理长字符串时性能较好

1

2

3

4

5

6

7

8

9

10

functiontrim3(str){

str = str.replace(/^(\s|\u00A0)+/,'');

for(vari=str.length-1; i>=0; i--){

if(/\S/.test(str.charAt(i))){

str = str.substring(0, i+1);

break;

}

}

returnstr;

}

最后需要提到的是 ECMA-262(V5) 中给String添加了原生的trim方法(15.5.4.20)。此外Molliza Gecko 1.9.1引擎中还给String添加了trimLefttrimRight 方法。

這是lgzx公司的一道面試題,要求給js的String添加一個方法,去除字符串兩邊的空白字符(包括空格、製錶符、換頁符等)

1

2

3

4

5

String.prototype.trim =function() {

//return this.replace(/[(^\s+)(\s+$)]/g,"");//會把字符串中間的空白符也去掉

//return this.replace(/^\s+|\s+$/g,""); //

returnthis.replace(/^\s+/g,"").replace(/\s+$/g,"");

}

JQuery1.4.2,Mootools 使用

1

2

3

functiontrim1(str){

returnstr.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g,'');

}

jQuery1.4.3,Prototype 使用,该方式去掉g以稍稍提高性能 在小规模的处理字符串时性能较好

1

2

3

functiontrim2(str){

returnstr.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,'');

}

Steven Levithan 在进行性能测试后提出了在JS中执行速度最快的裁剪字符串方式,在处理长字符串时性能较好

1

2

3

4

5

6

7

8

9

10

functiontrim3(str){

str = str.replace(/^(\s|\u00A0)+/,'');

for(vari=str.length-1; i>=0; i--){

if(/\S/.test(str.charAt(i))){

str = str.substring(0, i+1);

break;

}

}

returnstr;

}

最后需要提到的是 ECMA-262(V5) 中给String添加了原生的trim方法(15.5.4.20)。此外Molliza Gecko 1.9.1引擎中还给String添加了trimLefttrimRight 方法。