Skip to content

Instantly share code, notes, and snippets.

@vyspiansky
Created March 26, 2014 09:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vyspiansky/9779464 to your computer and use it in GitHub Desktop.
Save vyspiansky/9779464 to your computer and use it in GitHub Desktop.
JavaScript: trim function
function trim(str) {
var res = str.replace(/^\s+/, '');
return res.replace(/\s+$/, '');
}
@vyspiansky
Copy link
Author

Remove spaces from a string

if ('undefined' == typeof String.prototype.ltrim) {
    String.prototype.ltrim = function() {
        return this.replace(/^\s+/, '');
    }
}

if ('undefined' == typeof String.prototype.rtrim) {
    String.prototype.rtrim = function() {
        return this.replace(/\s+$/, '');
    }
}

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

// Usage:
var str = ' \n\t\r test \n\t\r ';
console.log('[' + str.ltrim() + ']');
console.log('[' + str.rtrim() + ']');
console.log('[' + str.trim() + ']');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment