Site logo


parseUnitValue function

This function parses strings as UnitValues and does unit conversions. converts a string, for instance "-10.1 yard" or "0,23 mm" or ".3 pt" to a UnitValue. And then returns this value converted to baseUnit for instance if s literally is "1 inch" or "1in" and baseUnit is "mm" the function will return 25.4 returns zero if the string doesn't parse to a UnitValue.


function Main() {
	var str = "1.5 in";
	var uv = parseUnitValue(str, "mm");

function parseUnitValue(s, baseUnit) { 
	if (s == undefined || s == '') { s = 0 } // if string empty make Zero 
	var regex = /(\-*\d*[\.|,]?\d*\s*)(in|inch|inches|ft|foot|feet|yd|yard|yards|mi|mile|miles|mm|millimeter|millimeters|cm|centimeter|centimeters|m|meter|meters|km|kilometer|kilometers|pt|point|points|pc|pica|picas|ci|cicero|ciceros)?/gi; 
	var myMatch = s.match(regex); 
	try { 
		var stringIsValid = ( s ==myMatch[ 0 ] ); // compare the string to the regular expression matched string. If they are equal then the string fits the required form for a unitvalue. 
	catch( e ) { 
		var stringIsValid = false; // if the string is not valid, something in the string was bad. Perhaps it was "+-10in" or "mommy" or "10i". Its not suitable for a unitvalue. 

	if (stringIsValid) { 
		var sVal = s.replace(regex, RegExp.$1).split(",").join("."); // get the real value part of the string. Also convert comma to point; 
		var sUnit = s.replace(regex, RegExp.$2); // get the unit part of the string. 
		if (sUnit == undefined || sUnit == "") { sUnit = baseUnit; } // this is for the case when the string is a number only, like "0", or "10.2", We then assume the user wanted the baseunit. 
	else { // if String doesn't parse as a unitvalue, make Zero 
		alert("Unknown Unit. Try: \n in, inch, inches, ft, foot, feet, yd, yard, yards, mi, mile, miles, pt, point, points, pc, pica, picas, ci, cicero, ciceros, \n mm, millimeter, millimeters, cm, centimeter, centimeters, m, meter, meters, km, kilometer, kilometers "); 
		var sVal = 0; 
		var sUnit = baseUnit; 

	var myUnitValue = new UnitValue(sVal, sUnit); // create a unitvalue object... 
	return; // ...but output its value only - converted to baseUnit