jquery.trim与string.trim相比 [英] jquery.trim compared to string.trim

查看:179
本文介绍了jquery.trim与string.trim相比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery trim和本机JavaScript one之间有什么区别吗?

Is there any difference between jQuery trim and native JavaScript one?

还有其他行为,安全性和性能吗?

Is there any other behaviour, safety, performance?

推荐答案

JavaScript .trim()在ES 5.1中定义,并且不适用于IE< 9 .因此,如果您已经使用jQuery,则可以使用性能较低的$.trim()

JavaScript .trim() was defined in ES 5.1, and will not work for IE<9. Therefore, if you already use jQuery you could use the less performant $.trim()

jQuery的 $.trim()方法可以:

trim: function( text ) {
    return text == null ? "" : ( text + "" ).replace( rtrim, "" );
}

其中rtrim基本上是此RegExp

where rtrim is basically this RegExp

new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" )

whitespace表示为该组:

"[\\x20\\t\\r\\n\\f]"


JavaScript (ES6)中定义为:


In JavaScript (ES6) it's defined as:

21.1.3.25 String.prototype.trim()

21.1.3.25 String.prototype.trim ( )

此函数将字符串值解释为UTF-16编码的代码点的序列,如6.1.4中所述.

This function interprets a String value as a sequence of UTF-16 encoded code points, as described in 6.1.4.

采取以下步骤: 令O为RequireObjectCoercible(此值). 令S为ToString(O). ReturnIfAbrupt(S). 令T为一个String值,它是S的副本,其中前导空格和尾随空格均已删除.空白的定义是WhiteSpace和LineTerminator的结合.确定Unicode代码点是否在Unicode通用类别"Zs"中时,代码单元序列将解释为6.1.4中指定的UTF-16编码的代码点序列. 返回T. 注:修整功能是有意通用的.它不需要其this值是String对象.因此,可以将其转移到其他类型的对象中用作方法.

The following steps are taken: Let O be RequireObjectCoercible(this value). Let S be ToString(O). ReturnIfAbrupt(S). 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. When determining whether a Unicode code point is in Unicode general category "Zs", code unit sequences are interpreted as UTF-16 encoded code point sequences as specified in 6.1.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.

因此,更不用说对浏览器供应商实施JS的.trim()了,这一点很明确:
从字符串的开头和结尾删除换行符或空格的任何表示形式.

So let alone the implementation of JS's .trim() to browser vendors, the point is quite clear:
Remove any representation of newlines or spaces from the beginning and end of a String.

这篇关于jquery.trim与string.trim相比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆