神刀安全网

Tailoring JavaScript Strings with trim

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 username :

var username = "dstorey ";

Trimming it in theconsole 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.

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » Tailoring JavaScript Strings with trim

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址