Skip to content

Instantly share code, notes, and snippets.

@jafstar
Created April 12, 2012 18:15
Show Gist options
  • Save jafstar/2369774 to your computer and use it in GitHub Desktop.
Save jafstar/2369774 to your computer and use it in GitHub Desktop.
Javascript Trim Strings
/*** FROM http://www.somacon.com/p355.php ***/
//BOTH
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
//LEFT
function ltrim(stringToTrim) {
return stringToTrim.replace(/^\s+/,"");
}
//RIGHT
function rtrim(stringToTrim) {
return stringToTrim.replace(/\s+$/,"");
}
//EXAMPLE
var myString = " hello my name is ";
alert("*"+trim(myString)+"*");
alert("*"+ltrim(myString)+"*");
alert("*"+rtrim(myString)+"*");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment