首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

javascript除去前导和后导空格的正则

2012-10-30 
javascript去除前导和后导空格的正则function trim(input_){var reg/(^\s+|\s+$)/gireturninput_.replac

javascript去除前导和后导空格的正则

function trim(input_){    var reg=/(^\s+|\s+$)/gi;    return  input_.replace(reg, function(march){          return march.replace(/\s+/,"");     }); }附replace的实现:  var GLOBAL = /(g|gi)$/;    var _String_replace = String.prototype.replace;     String.prototype.replace = function(expression, replacement) {      if (typeof replacement == "function") { // Safari doesn't like functions        if (expression && expression.constructor == RegExp) {         var regexp = expression;         var global = regexp.global;          //regexp.global 也不可靠?直接判断正则有没有g吧          if (global == null) global = GLOBAL.test(regexp);          // we have to convert global RexpExps for exec() to work consistently         //很精巧,即使是g 全局的也要剥离掉 ,使得全局不全局可以很统一和谐的对待          if (global) regexp = new RegExp(regexp.source); // non-global        } else {          regexp = new RegExp(rescape(expression));        }        var match, string = this, result = "";        while (string && (match = regexp.exec(string))) {          //匹配项替换后结果以及匹配前缀放入结果          result += string.slice(0, match.index) + replacement.apply(this, match);                    //这样很好,不用像chrome那样还要记录 previous 的状态,直接把要正则匹配的字符           串截断。          string = string.slice(match.index + match[0].length);                    //全局不全局只有这一个差别了          if (!global) break;        }                //最后一次匹配结束位置到字符串结尾        return result + string;     }      return _String_replace.apply(this, arguments);    };  

热点排行
Bad Request.