Created
December 26, 2014 19:17
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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   (thin space) or (non-breaking space) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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, ''); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The JavaScript code above is presently broken...