zoukankan      html  css  js  c++  java
  • Javascript中各种trim的实现

    這是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;
    }
    

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

  • 相关阅读:
    k3d安装k3s
    python自动目录环境
    http状态码
    linux下切换jdk版本
    pycharm py代码默认模板设置
    kubectl命令
    国内安装k3s
    minikube安装
    hmac-md5
    abstract class 与 interface
  • 原文地址:https://www.cnblogs.com/snandy/p/1965866.html
Copyright © 2011-2022 走看看