日期:2014-05-16 浏览次数:20345 次
ECMA-262(V5) 15.5.4.20 String.prototype.trim ( ) The following steps are taken: 1. Call CheckObjectCoercible passing the this value as its argument. 2. Let S be the result of calling ToString, giving it the this value as its argument. 3. Let T be a String value that is a copy of S with both leading and trailing white space removed. The definition of white space is the union of WhiteSpace and LineTerminator . 4. Return T. NOTE The trim function is intentionally generic; it does not require that its this value be a String object. Therefore, it can be transferred to other kinds of objects for use as a method.
String.prototype.trim = function() { //return this.replace(/[(^\s+)(\s+$)]/g,"");//會把字符串中間的空白符也去掉 //return this.replace(/^\s+|\s+$/g,""); // return this.replace(/^\s+/g,"").replace(/\s+$/g,""); }
function trim(str){ return str.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g, ''); }
function trim(str){ return str.replace(/^(\s|\u00A0)+/,'').replace(/(\s|\u00A0)+$/,''); }
function trim(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; }