jQuery in Action
168
CHAPTER 6
jQuery utility functions
designed to operate on the
DOM
is provided as a jQuery command. Although
some of these functions can be used to operate on
DOM
elements--which are
JavaScript objects, after all--the focus of the utility functions isn't
DOM
-centric.
Let's start with one that's basic.
6.3.1 Trimming strings
Almost inexplicably, the JavaScript
String
implementation doesn't possess a
method to remove whitespace characters from the beginning and end of a string
instance. Such basic functionality is customarily part of a
instance. Such basic functionality is customarily part of a
String
class in most
other languages, but JavaScript mysteriously lacks this useful feature.
Yet string trimming is a common need in many JavaScript applications; one
prominent example is form data validation. Because whitespace is invisible on the
screen (hence its name), it's easy for users to accidentally enter extra space charac-
ters after (or sometimes even before) valid entries in text boxes or text areas. Dur-
ing validation, we want to silently trim such whitespace from the data rather than
alerting the user to the fact that something that they can't see is tripping them up.
screen (hence its name), it's easy for users to accidentally enter extra space charac-
ters after (or sometimes even before) valid entries in text boxes or text areas. Dur-
ing validation, we want to silently trim such whitespace from the data rather than
alerting the user to the fact that something that they can't see is tripping them up.
To help us out, jQuery defines the
$.trim()
function as follows:
A small example of using this function to trim the value of a text field in-place is
$('#someField').val($.trim($('#someField').val()));
Be aware that this function doesn't check the parameter we pass to ensure that it's
a String value, so we'll likely get undefined and unfortunate results (probably a
JavaScript error) if we pass any other value type to this function.
a String value, so we'll likely get undefined and unfortunate results (probably a
JavaScript error) if we pass any other value type to this function.
Now let's look at some functions that operate on arrays and other objects.
Function syntax: $.trim
$.trim(value)
Removes any leading or trailing whitespace characters from the passed string and returns
the result.
Whitespace characters are defined by this function as any character matching the JavaScript
regular expression
the result.
Whitespace characters are defined by this function as any character matching the JavaScript
regular expression
\s
, which matches not only the space character but also the form feed,
new line, return, tab, and vertical tab characters, as well as the Unicode characters \u00A0,
\u2028
\u2028
, and \u2029.
Parameters
value
(String) The string value to be trimmed. This original value isn't modified.
Returns
The trimmed string.
The trimmed string.