jquery and java .properties files

I recently had a need to parse a Java .properties format file in Javascript, and couldn’t find a suitable library for it, so I hacked out this (actually I copied the regular expressions from a Perl implementation):

/**
 * parse a string containing text in Java .properties file format, and convert it into a map
 * Based on the Perl module Config::Properties
 *
 * jQueryAuthor: Edward
 */
jQuery.parseProperties = function(propertiestext)
{
	var propertyMap = {};
	var lines = propertiestext.split(/\r?\n/);
	var currentLine = '';
	jQuery.each(lines, function(i, value)
	{
		//check if it is a comment line
		if (!/^\s*(\#|\!|$)/.test(value)) // line is whitespace or first non-whitespace character is '#' or '!'
		{
			value = value.replace(/^\s*/, ''); // remove space at start of line
			currentLine += value;
			if (/(\\\\)*\\$/.test(currentLine)) // line ends with an odd number of '\' (backslash)
			{
				//line ends with continuation character, remember it and don't process further
				currentLine = currentLine.replace(/\\$/, '');
			}
			else
			{
				/^\s*((?:[^\s:=\\]|\\.)+)\s*[:=\s]\s*(.*)$/.test(currentLine); // sub-matches pick out key and value
				var nkey = RegExp.$1;
				var nvalue = RegExp.$2;
 
				propertyMap[nkey] = nvalue;
 
				currentLine = '';
			}
		}
	});
 
	return propertyMap;
};

It doesn’t particularly require jQuery, but I like the each iterator.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*