User-submitted text entered intoforms is often padded with spaces, usually generated by accidentally hitting the space bar inside atext 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 avariable
var username = "dstorey ";
Trimming it in theconsole will create:
console.log(username.trim()); > "dstorey"
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 (
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.