» Programming » JavaScript » String.trim()

This code snippet adds the String.trim() function, making it available to ALL String objects in JavaScript. This function will remove all white-space at the beginning and end of the string, returning the new string.

1
2
3
4
5
if ((typeof String.prototype.trim) == "undefined") {
  String.prototype.trim = function() {
    return this.replace(/^\s+/,'').replace(/\s+$/,'');
  }
}