I have developed a JavaScript function to convert a decimal number of inches to a string displaying feet, inches, and fractional components - for example, 23.75 inches converts to 1' 11 3/4". (To my surprise, this appears not to be available 'pre-cooked' anywhere I can find using Google.)
It will normally be used to convert to 'woodworking' fractions: halves, quarters, eighths, sixteenths, thirtyseconds, etc., where the denominator is a power of two. But I also want it to accept (subject to a warning and confirmation prompt) any other denominator.
The function takes two parameters: the length in inches with optional decimal, and a precision (integer number) for the denominator to use for the fractional component (if any).
I am attempting to detect whether the precision is a power of two, and prompt for confirmation if it isn't.
The code snippet looks like this:
Code:
// Check if denominator is a power of two and warn if not
denom = precision.toString().match(/32|16|8|4|2/);
if(!denom) { // Denominator isn't regular woodworking fraction
ok = confirm("Fraction isn't the usual woodworking half, quarter, eighth, sixteenth etc. Did you mean this?",false);
if (!ok) {//code continues....
}
I would expect the Regex to trigger a confirmation prompt if the input
precision is
not 2, 4, 8, 16, or 32.
But it returns a value of 2 (true) for precision = 12, and therefore doesn't trigger the alert, which I don't understand. It does trigger for precision = 3 or 6.
The same expressionn in Java (not JavaScript) works as I expected, returning a match only if the string matches exactly one of the numbers in the Regex.
Am I misunderstanging how the Regex match() function is supposed to work in JS? If so, why, and how can I otherwise detect and warn when the requested precision isn't a power of two? I could (but don't want to) code it explicitly to work out mathematically if precision is a power of two between 2 and 64, but would prefer to understand and use properly a Regex to detect this.
Help welcome, if anyone can point me to a Regex tutorial specific to JavaScript, or explain what this regex is doing and why.
Thanks.
John McC