Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save xxl007/11125176 to your computer and use it in GitHub Desktop.
Save xxl007/11125176 to your computer and use it in GitHub Desktop.
Trimming Whitespace from the Ends of a String
// Using the trim method (trimLeft and trimRight methods also exist)
var txtBox = document.getElementById("test");
var line = txtBox.value.split("\n");
var resultString = "";
for (var i=0; i < lines.length; i++) {
var strng = lines[i].trim();
resultString += strng + "-";
}
alert(resultString);
// Workaround in case trim method not supported in browser (pre ECMAScript 5)
// adding customised trim method to the String object
// Subsequently call the trim method on any String
if (typeof String.trim == "undefined") {
String.prototype.trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, "");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment