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
alert(“!” + s + “!”);
// end hiding contents –> </script>

Thanks to this site!


5 thoughts on “trim in Javascript!

  1. Copy & paste then manipulate to your needs. That is what Google has me doing these days. I see it as like reverse engineering.

  2. Please help,

    I have this: String parentPersonID = request.getParameter(“parentPersonID”);

    and this is where it is called from:

    Enter a Parent’s PersonID, then generate report:

    I need to trim spaces before I sent parentPersonID to an url. I tried this:
    String parentPersonID = request.getParameter(“parentPersonID”).replace(/^\s+|\s+$/g, ”) ;

    , but I get and error message saying:
    type Exception report


    description The server encountered an internal error () that prevented it from fulfilling this request.


    org.apache.jasper.JasperException: Unable to compile class for JSP:

    An error occurred at line: 82 in the jsp file: /alachua/householdGUID.jsp
    Syntax error on tokens, delete these tokens
    80: <%
    82: String parentPersonID = request.getParameter("parentPersonID").replace(/^\s+|\s+$/g, '') ;

    Any help would be greately appreciated.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s