Skip to main content

JavaScript trim string function. Also, left and right trim individually.

// checks for native trim before extending
if (!String.prototype.trim) {
  String.prototype.trim = function () {
    var str = this.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
      if (/\S/.test(str.charAt(i))) {
        str = str.substring(0, i + 1);
        break;
      }
    }
    return str;
  };
}

String.prototype.ltrim = function() {
  return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
  return this.replace(/\s+$/,"");
}

// Stand-alone trim functions
// http://www.somacon.com/p355.php
function trim(stringToTrim) {
  return stringToTrim.replace(/^\s+|\s+$/g, "");
}

function ltrim(stringToTrim) {
  return stringToTrim.replace(/^\s+/, "");
}

function rtrim(stringToTrim) {
  return stringToTrim.replace(/\s+$/, "");
}