JavaXT

Miscellaneous JavaScripts

How to Trim a String

JavaScript doesn't include a trim method natively, although some browsers (e.g. Firefox) do seem to support it. Still, if you're writing a cross browser app, you need to provide your own trim method. Here's a really simple regex you can use:
var str = " Hello World! ".replace(/^\s*/, "").replace(/\s*$/, "");
Of course, you can extend the native string class to include a trim() method like this:
  //Declare the string prototype
    String.prototype.trim = function() {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    }

  //Now you can call the trim method like this:
    var str = " Hello World! ".trim();

Get URL QueryString Parameters

Here's a cool little script I found to parse querystring parameters using regular expressions.

function getParameter( name ){
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if (results == null) return "";
    else return results[1];
}

Source: http://www.netlobo.com/url_query_string_javascript.html

How to Get the Name of an Object

Here's a handy little script to get the name of an object.

    var getClassName = function(obj) {
        var c = obj.constructor.toString();
        return c.substring(c.indexOf('function ') + 9, c.indexOf('('));
    };

Source: http://answers.yahoo.com/question/index?qid=20080317124005AAcF5P2

How to Convert a String into JSON

    var obj = eval("(function(){return " + str + ";})()");