parseUri 1.2: Split URLs in JavaScript

This code was originally posted by Steve in ‘http://blog.stevenlevithan.com/archives/parseuri’. I just copied from his blog. You can get details about this function to above url. This is very efficient and useful function for url parsing.

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};
Advertisements

Javascript manipulate contents by class name like ID

Most of us use ID to access or manipulate html DOM, But it can be done with class name which is little bit tricky. I have done it on one of my firefox plugin project.


var target_class = document.getElementsByClassName("div_content")[0];// Search the class
clearChildNodes(target_class);//Remove Child nodes of the class

var div1 = document.createElement("div");//create a new element
div1.setAttribute('class', 'child_div1');// Add class name to the newly created element

target_class .appendChild(div1);// Append the new element to the target div


function clearChildNodes(node) {
    if (node.childNodes.length &gt; 0) {
        while(node.hasChildNodes()) {
            node.removeChild(node.firstChild);
        }
    }
    return node;
}

Money Format(us currency)

    
formatCurrency:function (num) {
        num = num.toString().replace(/\$|\,/g,'');
        if(isNaN(num))
            num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num*100+0.50000000001);
        cents = num%100;
        num = Math.floor(num/100).toString();
        if(cents<10)
            cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
            num = num.substring(0,num.length-(4*i+3))+','+
            num.substring(num.length-(4*i+3));
            if(cents==00) return (((sign)?'':'-') + num );
            else
            return (((sign)?'':'-') + num + '.' + cents);
    }