Skip to content

Instantly share code, notes, and snippets.

@matthewpenkala
Forked from csharpforevermore/WhitespaceRemover.js
Last active March 3, 2023 14:59
Show Gist options
  • Save matthewpenkala/8ab0576c702b9aabfef9ee6be4692e1e to your computer and use it in GitHub Desktop.
Save matthewpenkala/8ab0576c702b9aabfef9ee6be4692e1e to your computer and use it in GitHub Desktop.
Remove whitespace in JavaScript [FORK] – Sourced from https://css-tricks.com/snippets/javascript/strip-whitespace-from-string/
// 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, '');
}
@matthewpenkala
Copy link
Author

matthewpenkala commented Mar 3, 2023

      This will appear with six space characters in front of it.

     This will appear with six space characters in front of it.

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