jquery.trim compared to string.trim

萝らか妹 提交于 2020-04-12 15:24:55

问题


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

Is there any other behaviour, safety, performance?


回答1:


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's $.trim() Method does:

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

where rtrim is basically this RegExp

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

and whitespace is represented as this Group:

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


In JavaScript (ES6) it's defined as:

21.1.3.25 String.prototype.trim ( )

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

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.

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.




回答2:


String.trim

The trim() method removes whitespace from both sides of a string.

Note: The trim() method does not change the original string.

var str = "       Hello World!        ";
alert(str.trim());

jquery.trim()

The $.trim() function removes all newlines, spaces (including non-breaking spaces), and tabs from the beginning and end of the supplied string.

If these whitespace characters occur in the middle of the string, they are preserved



来源:https://stackoverflow.com/questions/40329177/jquery-trim-compared-to-string-trim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!