User-submitted text entered into forms is often padded with spaces, usually generated by accidentally hitting the space bar inside a text input. Site owners almost always want to erase this extra data: it would be confusing for a user to have their login attempt rejected just because their original signup included an unseen space.
Removing spaces - which covers spaces, tab, no-break spaces, carriage returns and line feed characters - is the function of the trim()
method. Given a variable username
:
var username = "dstorey ";
Trimming it in the console will create:
console.log(username.trim());
> "dstorey"
More frequently, the result of a trim()
is set to a variable. Given a text input
with an id
and name
of username
:
var username = document.getElementById("username").value.trim();
Developers often use the term “trim” when referring to removing characters in general: for example “trimming off a file extension” or “trimming the first character”. Technically, trim()
is only relevant to removing spaces, and all other actions will use other methods (replace()
and slice
respectively, in the examples provided.)
Support & Alternatives
trim()
is functionally equivalent to JQuery’s $.trim(str)
; the native method is supported in all modern browsers, including IE9+ and Safari 5, so it’s advisable to use the native trim()
unless historical browser support is required.
Photograph by Fred Fraser, licensed under Creative Commons.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.