Implementing String.trim() in Javascript
Curiously, the String class in javascript does not natively expose a trim() method. Not a problem! Since it is a dynamic language, javascript allows you the ability to crack open a class and add new functionality to it.
<script language="javascript" type="text/javascript">
String.prototype.trim = function() {
return this.replace(/^\s+/,"").replace(/\s+$/,"");
}
var s = new String(" Test me! ").trim();
alert("'" + s + "'");
</script>
The prototype keyword indicates that you are adding functionality to an existing class. In this case, we are adding a method called trim() to the String class that uses regular expressions to find any spaces (\s+ = one or more whitespace characters) at the beginning (^ = match at the START of a line) and then the end ($ = match at the END of a line) of the string, and replace the spaces we find with an empty string ("").
Tuesday, May 13, 2008 11:07:44 AM (Eastern Standard Time, UTC-05:00)
Javascript