Javascript Trim LTrim and RTrim Functions

/ Published in: JavaScript
Save to your folder(s)

his set of Javascript functions trim or remove whitespace from the ends of strings. These functions can be stand-alone or attached as methods of the String object. They can left trim, right trim, or trim from both sides of the string. Rather than using a clumsy loop, they use simple, elegant regular expressions.

Copy this code and paste it in your HTML
  1. String.prototype.trim = function() {
  2. return this.replace(/^\s+|\s+$/g,"");
  3. }
  4. String.prototype.ltrim = function() {
  5. return this.replace(/^\s+/,"");
  6. }
  7. String.prototype.rtrim = function() {
  8. return this.replace(/\s+$/,"");
  9. }


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.