/*
 * StrUtils.js - Version 0.1
 *
 * $Id: StrUtils.js 24 2009-08-14 12:28:13Z terence $
 *
 * Copyright (c) 2008 Terence Honles (terence.honles.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 */

String.prototype.formatPattern = /({?){([^}]+)}(}?)/g;


String.prototype.format = function() {
	var args = arguments;

	if (args.length == 1) {
		var arg1 = args[0];
		if (typeof arg1 == 'object' && arg1 != null && arg1.constructor != String) {
			args = arg1;
		}
	}

	var split = this.split(this.formatPattern);
	var sub = new Array();

	for (var i = 0, len = split.length;i < len; i += 4) {
		sub.push(split[i]);
		if (len > i+3) {
			var left = split[i+1];
			var key = split[i+2];
			var right = split[i+3];
			if (left == '{' && right == '}') sub.push(left, key, right);
			else {
				key = key.strip();
				if (!(key in args))
					 throw new Error('field {' + key + '} was not found');
				sub.push(left, args[key], right);
			}
		}
	}
	
	return sub.join('')
}

String.prototype.strip = function (toStrip) {
	if (!toStrip) toStrip = '\\s+';
	else if (toStrip.source) toStrip = toStrip.source; // incase of a RegExp

	return this.replace(new RegExp('^' + toStrip + '|' + toStrip + '$'), '');
}


String.prototype.lstrip = function(toStrip) {
	if (!toStrip) toStrip = '\\s+';
	else if (toStrip.source) toStrip = toStrip.source; // incase of a RegExp

	return this.replace(new RegExp('^' + toStrip), '');
}

String.prototype.rstrip = function(toStrip) {
	if (!toStrip) toStrip = '\\s+';
	else if (toStrip.source) toStrip = toStrip.source; // incase of a RegExp

	return this.replace(new RegExp(toStrip + '$'), '');
}

