Skip to content

Instantly share code, notes, and snippets.

@csharpforevermore
Created December 26, 2014 19:17
Show Gist options
  • Save csharpforevermore/6647c3400ce674f11a60 to your computer and use it in GitHub Desktop.
Save csharpforevermore/6647c3400ce674f11a60 to your computer and use it in GitHub Desktop.
Remove whitespace in JavaScript. Sourced from http://css-tricks.com/snippets/javascript/strip-whitespace-from-string/
// Remove leading and trailing whitespace
// jQuery $.trim
var str = " a b c d e f g ";
var newStr = $.trim(str);
$("body").append("<div>" + newStr + "</div>");
// Remove leading and trailing whitespace
// JavaScript RegEx
var str = " a b c d e f g ";
var newStr = str.replace(/(^\s+|\s+$)/g,'');
$("body").append("<div>" + newStr + "</div>");
// Remove all whitespace
// JavaScript RegEx
var str = " a b c d e f g ";
var newStr = str.replace(/\s+/g, '');
$("body").append("<div>" + newStr + "</div>");
// Native JavaScript method
// Polyfill it just in case
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
var str = " a b c d e f g ";
var newStr = str.trim();
$("body").append("<div>" + newStr + "</div>");
// None of these work for &#8239; (thin space) or &nbsp; (non-breaking space)
// Vanilla JavaScript - trim Leading and Trailing - ES5
function TrimVanilla(str){
return str.trim();
}
// Older browsers - IE8 and before - using Polyfill. Call trim() method after running this.
function TrimPolyfill(){
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
}
}
// jQuery (Trim Leading and Trailing)
function TrimWithjQuery(str){
return $.trim(str);
}
// Vanilla JavaScript RegEx (Trim Leading and Trailing)
function TrimWithjQuery(str){
return str.replace(/(^\s+|\s+$)/g,'');
}
// Vanilla JavaScript RegEx (Trim ALL Whitespace)
function TrimWithjQueryAll(str){
return str.replace(/\s+/g, '');
}
@matthewpenkala
Copy link

The JavaScript code above is presently broken...


whitespaceJS_fixed (1)

// Vanilla JavaScript - trim Leading and Trailing - ES5
function TrimVanilla(str) {
  return str.trim();
}

// Older browsers - IE8 and before - using Polyfill. Call trim() method after running this.
function TrimPolyfill() {
  if (!String.prototype.trim) {
    String.prototype.trim = function () {
      return this.replace(/^\s+|\s+$/g, '');
    };
  }
}

// jQuery (Trim Leading and Trailing)
function TrimWithjQuery(str) {
  return $.trim(str);
}

// Vanilla JavaScript RegEx (Trim Leading and Trailing)
function TrimWithVanilla(str) {
  return str.replace(/(^\s+|\s+$)/g, '');
}

// Vanilla JavaScript RegEx (Trim ALL Whitespace)
function TrimWithVanillaAll(str) {
  return str.replace(/\s+/g, '');
}

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