trim in Javascript!

So, Javascript has no trim option. Its truE!!
So here is two quick workarounds,

var trimmed = str.replace(/^\s+|\s+$/g, ”) ;

Thanks to nicknettleton!

Second one is,

// implementing a trim function for strings in javascript
<script language=”JavaScript” type=”text/javascript”>
<!–
String.prototype.trim = function () {
return this.replace(/^\s*/, “”).replace(/\s*$/, “”);
}var s = new String(” Hello “);
// use it like this
s=s.trim();
alert(“!” + s + “!”);
// end hiding contents –> </script>

Thanks to this site!

1 Comment »

  1. Silent Walker said

    I always wonder whether there is a need to learn Javascript when we’ve google! :D

RSS feed for comments on this post · TrackBack URI

Leave a Comment