Possible Duplicate:
Regex/Javascript to transform Degrees Decimal Minutes to Decimal Degrees
I have some javascript code that converts Decimal Degree Minutes to Decimal Degrees. But something is slightly screwy and am hoping someone here will know how to fix it.
How to I get this to consistently work when a user removes the °
or has extra spaces?
With the °
character it works great:
input "77° 50.51086497"
output "77.8418477495"
input "-113° 40.54687527"
output "-113.6757812545"
However without the °
it sometimes breaks:
NOT WORKING
input "77 50.51086497"
ouput "775.0085144161667"
WORKING
input "-113 40.54687527"
output "-113.6757812545"
Same thing with extra spaces:
NOT WORKING
input "77 ` ` ` ` ` ` ` `50.51086497"
output "775.0085144161667"
WORKING
input "-113 ` ` ` ` ` ` ` `40.54687527 "
output "-113.6757812545"
Here is my code: Please see the JSFIDDLE TO TEST
function ddmToDeg(ddm) {
if (!ddm) {
return Number.NaN;
}
var neg= ddm.match(/(^\s?-)|(\s?[SW]\s?$)/)!=null? -1.0 : 1.0;
ddm= ddm.replace(/(^\s?-)|(\s?[NSEW]\s?)$/,'');
ddm= ddm.replace(/\s/g,'');
var parts=ddm.match(/(\d{1,3})[.,°d]?(\d{0,2}(?:\.\d+)?)[']?/);
//dms.match(/(\d{1,3})[.,°d]?(\d{0,2})[']?(\d{0,2})[.,]?(\d{0,})(?:["]|[']{2})?/);
if (parts==null) {
return Number.NaN;
}
// parts:
// 0 : degree
// 1 : degree
// 2 : minutes
var d= (parts[1]? parts[1] : '0.0')*1.0;
var m= (parts[2]? parts[2] : '0.0')*1.0;
var dec= (d + (m/60.0))*neg;
return dec;
}