Home >Web Front-end >JS Tutorial >Detailed explanation of jQuery.trim() function and trim() usage_jquery

Detailed explanation of jQuery.trim() function and trim() usage_jquery

WBOY
WBOYOriginal
2016-05-16 15:34:592553browse

The jQuery.trim() function is used to remove whitespace characters at both ends of a string. This function removes whitespace characters at the beginning and end of a string (until the first non-whitespace string is encountered). It will remove common whitespace characters including newlines, spaces, tabs, etc.

This function belongs to the global jQuery object.

Grammar

jQuery 1.0 added this static function.

jQuery.trim( str )

参数 描述
str String类型需要去除两端空白字符的字符串。

If the parameter str is not of string type, this function will automatically convert it to a string (usually calling its toString() method). If the parameter str is null or undefined, an empty string ("") is returned.

Return value

The return value of the jQuery.trim() function is of String type, returning the string after removing the blank strings at both ends.

Examples & Instructions

The following is jQuery sample code related to the jQuery.trim() function to demonstrate the specific usage of the jQuery.trim() function:

//在当前页面内追加换行标签和指定的HTML内容
function w( html ){
  document.body.innerHTML += "<br/>" + html;
}
// 输出两侧添加双引号,以便于区分字符串边界
w( '"' + $.trim( "  CodePlayer  " ) + '"'); // "CodePlayer"
// 只会去除两端的连续空白字符
w( '"' + $.trim( "  Code Player  " ) + '"'); // "Code Player"
w( '"' + $.trim( "\r\n\t  CodePlayer  \t" ) + '"'); // "CodePlayer"
w( '"' + $.trim( "" ) + '"'); // ""
w( '"' + $.trim( 12 ) + '"'); // "12"
w( '"' + $.trim( null ) + '"'); // ""
w( '"' + $.trim( undefined ) + '"'); // ""
w( '"' + $.trim( new Object() ) + '"'); // "[object Object]"

Usage of trim() in jquery

<html>
<head>
<title>$.trim()</title>
<script language="javascript" src="jquery.min.js"></script>
<script language="javascript">
var sString = " 1234567890 ";
sString = $.trim(sString);
alert(sString.length);
</script>
</head>
<body>
</body>
</html>

If you develop a website under the IE8 browser, this is actually a false proposition, because native javascript does not support the .trim() method. If you write code similar to document.getElementByID().trim(); When running in IE8 mode, an error will be reported: The method or attribute is not supported.

The solution is as follows:

1. Use $.trim([object to be operated on]);

provided by JQuery

2. Encapsulate a method to intercept blank characters.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn