Skip to content

Instantly share code, notes, and snippets.

@ianpgall
Last active December 20, 2015 00:28
Show Gist options
  • Save ianpgall/6041486 to your computer and use it in GitHub Desktop.
Save ianpgall/6041486 to your computer and use it in GitHub Desktop.
JavaScript function to trim Strings (detects native browser support)
var Trim = (function () {
"use strict";
var S, both, left, right;
S = "";
if (S.trim && !S.hasOwnProperty("trim")) {
both = function (str) {
return S.trim.call(str);
};
left = function (str) {
return S.trimLeft.call(str);
};
right = function (str) {
return S.trimRight.call(str);
};
} else {
both = (function () {
var re, ret;
re = /^\s+|\s+$/g;
ret = function (str) {
str = "" + (str || "");
return str.replace(re, "");
};
return ret;
}());
left = (function () {
var re, ret;
re = /^\s+/g;
ret = function (str) {
str = "" + (str || "");
return str.replace(re, "");
};
return ret;
}());
right = (function () {
var re, ret;
re = /\s+$/g;
ret = function (str) {
str = "" + (str || "");
return str.replace(re, "");
};
return ret;
}());
}
return {
both: both,
left: left,
right: right
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment