js trim函数
来源:互联网 发布:linux postgresql 编辑:程序博客网 时间:2024/06/06 12:46
实现1
String.prototype.trim =
function
() {
return
this
.replace(/^\s\s*/,
''
).replace(/\s\s*$/,
''
);
}
实现2
String.prototype.trim =
function
() {
return
this
.replace(/^\s+/,
''
).replace(/\s+$/,
''
);
}
实现3
String.prototype.trim =
function
() {
return
this
.substring(Math.max(
this
.search(/\S/), 0),
this
.search(/\S\s*$/) + 1);
}
以截取方式取得空白部分(当然允许中间存在空白符),总共调用了四个原生方法。设计得非常巧妙,substring以两个数字作为参数。Math.max以两个数字作参数,search则返回一个数字。速度比上面两个慢一点,但比下面大多数都快。
实现4
String.prototype.trim =
function
() {
return
this
.replace(/^\s+|\s+$/g,
''
);
}
这个可以称得上实现2的简化版,就是利用候选操作符连接两个正则。但这样做就失去了浏览器优化的机会,比不上实现3。由于看来很优雅,许多类库都使用它,如JQuery与mootools
实现5
String.prototype.trim =
function
() {
var
str =
this
,
whitespace =
' \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000'
;
for
(
var
i = 0,len = str.length; i < len; i++) {
if
(whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(i);
break
;
}
}
for
(i = str.length - 1; i >= 0; i--) {
if
(whitespace.indexOf(str.charAt(i)) === -1) {
str = str.substring(0, i + 1);
break
;
}
}
return
whitespace.indexOf(str.charAt(0)) === -1 ? str :
''
;
}
实现6
String.prototype.trim =
function
() {
var
str =
this
,
str = str.replace(/^\s+/,
''
);
for
(
var
i = str.length - 1; i >= 0; i--) {
if
(/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break
;
}
}
return
str;
}
实现7
String.prototype.trim =
function
() {
var
str =
this
,
str = str.replace(/^\s\s*/,
''
),
ws = /\s/,
i = str.length;
while
(ws.test(str.charAt(--i)));
return
str.slice(0, i + 1);
}
- js trim函数
- js trim函数
- js实现trim函数
- Js中的trim函数
- js trim 函数
- JS完成trim函数
- js trim函数
- js编写trim()函数
- js trim函数
- js定义trim函数
- JS编写Trim函数
- js中trim函数
- JS trim()函数的实现
- js trim() 函数 及 方法
- js实现类似trim函数
- js中没有trim()函数
- js的trim(),Ltrim(),Rtrim()函数
- js 的Trim、LTrim、RTrim函数
- 回家看是否节目将规划
- 用js保存页面指定内容
- s3c2440,s3c6410,s5p6450地址空间和连线
- 免费实用微软系统工具集推荐
- juniper/cisco commands
- js trim函数
- C 关键字
- windows下如何获取系统音量(使用mixer api)
- Win7 Win8建立扩展分区的方法
- android:点击popupwindow以外区域 popupwindow自动消失
- c++模板类
- php+mysql中文数据乱码问题的解决
- 8张图助你更好的理解java编程
- Windows2003终端服务授权激活