Skip to main content
Inspiring
August 17, 2008
Question

converting String to UnitValues?

  • August 17, 2008
  • 5 replies
  • 1344 views
Hello,
how would i convert a string object to a UnitValue object?
Say i have a an editbox.text where the user entered the string "2 in".
How do i make it a unitvalue so i can convert it to another unit?

regards,
Stephan
This topic has been closed for replies.

5 replies

Inspiring
August 18, 2008
Thanks again, Bob. I would never have figured it out myself.
Here is a String to UnitValue conversion example that works for me:

//
str = "-10,1mm";
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 = str.match( regex );
alert(myMatch);

try {
var fieldIsValid = ( str ==str.match( regex )[ 0 ] );
} catch( e ) {
var fieldIsValid = false;
}

var myVal = str.replace(regex, RegExp.$1).split(",").join(".");
var myUnit = str.replace(regex, RegExp.$2);

alert(myVal);
alert(myUnit);

if (fieldIsValid) {
var myUnitValue = new UnitValue(myVal, myUnit);
alert(myUnitValue +' is a UnitValue now' );
alert('can be converted easily now to inch: ' + myUnitValue.as("in"));
}
Inspiring
August 18, 2008
And here is the resulting function that parses strings as Unitvalues and does unit conversions.

var str = Edittext.text; // user enters "10in" or "-1 pt" or anything
var unitval = parseUnitValue(str, "mm");
Edittext.text = unitval;

function parseUnitValue (s, baseUnit) {
// it's beautiful!
// 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!
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 myUnitValue.as(baseUnit); // ...but output its value only - converted to baseUnit
}
Inspiring
August 18, 2008
Very nice chunk of code Bob!

I don't know why I wrote the bit about needing a space between the number and the unit type. I could have sworn that I couldn't get that to work yesterday. I just retested, and it works fine--I guess I was just hallucinating. Again. ;-)

-- Jim
August 18, 2008
To validate the input field, this will work:

var regex = /\-*\d*\.{0,1}\d* *(?: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 = myString.match( regex );
try {
var fieldIsValid = ( myEvent.target.text == myEvent.target.text.match( regex )[ 0 ] );
} catch( e ) {
var fieldIsValid = false;
}

That will validate a real number, one or more spaces, followed by units accepted by UnitValue

Bob
Inspiring
August 18, 2008
Thank you very much! Can't wait to get home and try it in my script.
August 18, 2008
var a = new UnitValue( "10 in" );
a.as( "mm" );

output is 254

It won't parse 4p3, but it will correctly parse a string such as "10 in", "27pt", or "12cm".

Bob
Inspiring
August 18, 2008
Thank you for your help, too. My problem is a little bit different. Perhaps i didn't describe it well enough. Can you still help me?

I have an editbox where the user enters a String. He enters anything he likes really - hopefully a proper unitvalue. But the editbox.text object is a String. And there is no telling what the user might enter:
"10 in", "10in", "10 inch", "10 inches", "10mm", "10", "Mommy"

How do i parse this string to become the proper unitValue object "10 in"?
Inspiring
August 18, 2008
Hi Stephan,

You got me curious as to how to use this, so I did some experimentation. At the end of the message is the code I came up with. I have not used UnitValue before, so hopefully others will chime if my code has some errors in it.

I noticed that UnitValue doesn't seem as sophisticated as InDesign's built in value parsing. For example, I couldn't figure out a way to use "6p7" (6 picas plus 7 points) in the constructor and have UnitValue know what it means. Also, one needs to make sure that there is a space between the value (the number) and the unit name in the string.

I could not quickly find a list of valid unit names, so I just made some guesses and listed the ones that worked.

The output prints to ExtendScript Tookkit's console panel.

I hope this helps!

-- Jim


// Using UnitValue.
// Create a new instance of a UnitValue object

var myUV = new UnitValue("72 pt");

if (myUV.type == "?")

{

$.writeln("Unknown unit type entered.");

}

else

{

// Get the value in a particular measurement unit

$.writeln("Inches: " + myUV.as("in"));

$.writeln("Inches: " + myUV.as("inch"));

$.writeln("Millimeters: " + myUV.as("mm"));

$.writeln("Points: " + myUV.as("pt"));

$.writeln("Picas: " + myUV.as("pica"));

$.writeln("Ciceros: " + myUV.as("cicero"));



// Convert the UnitValue object to a specific measurement unit



// Show before conversion unit value output:

$.writeln("Before conversion: " + myUV);



// Convert the UnitValue into inches

myUV.convert("in");



// Show after conversion unit value output

$.writeln("After conversion: " + myUV);



}

Inspiring
August 18, 2008
Thanks for jumping in. A list of unitnames and a description of the function i found in the adobe scripting guide.

How would you convert a string to a unitvalue? How would you write a "parseUnitValue(str)" function?

Say the user enters the string "10 pt", or "10 in" or "10 mm".
Somehow i would have to seperate the value 10 from the substring "pt"/"mm"/"in" or whatever the user enters as unit. Seperated in substrings it could be fed to a new UnitValue(value, substring).

I found the string.match() function, which seems to be able to seperate the string into the needed parts. But i don't know how to make it work.