@@ -148,18 +148,24 @@ class Mgrs {
148
148
*
149
149
* @example
150
150
* const mgrsRef = Mgrs.parse('31U DQ 48251 11932');
151
- * const mgrsRef = Mgrs.parse('31UDQ4825111932');
151
+ * const mgrsRef = Mgrs.parse('31UDQ4825111932'); // military style no separators
152
152
* // mgrsRef: { zone:31, band:'U', e100k:'D', n100k:'Q', easting:48251, northing:11932 }
153
153
*/
154
154
static parse ( mgrsGridRef ) {
155
155
if ( ! mgrsGridRef ) throw new Error ( `invalid MGRS grid reference ‘${ mgrsGridRef } ’` ) ;
156
156
157
157
// check for military-style grid reference with no separators
158
- if ( ! mgrsGridRef . trim ( ) . match ( / \s / ) ) {
159
- if ( ! Number ( mgrsGridRef . slice ( 0 , 2 ) ) ) throw new Error ( `invalid MGRS grid reference ‘${ mgrsGridRef } ’` ) ;
160
- let en = mgrsGridRef . trim ( ) . slice ( 5 ) ; // get easting/northing following zone/band/100ksq
161
- en = en . slice ( 0 , en . length / 2 ) + ' ' + en . slice ( - en . length / 2 ) ; // separate easting/northing
162
- mgrsGridRef = mgrsGridRef . slice ( 0 , 3 ) + ' ' + mgrsGridRef . slice ( 3 , 5 ) + ' ' + en ; // insert spaces
158
+ if ( ! mgrsGridRef . trim ( ) . match ( / \s / ) ) { // replace with standard space-separated format
159
+ const milref = mgrsGridRef . match ( / ( \d \d ? [ A - Z ] ) ( [ A - Z ] { 2 } ) ( [ 0 - 9 ] { 2 , 10 } ) / ) ;
160
+ if ( ! milref ) throw new Error ( `invalid MGRS grid reference ‘${ mgrsGridRef } ’` ) ;
161
+ const mil = {
162
+ gzd : milref [ 1 ] ,
163
+ en100k : milref [ 2 ] ,
164
+ en : milref [ 3 ] ,
165
+ } ;
166
+ mil . e = mil . en . slice ( 0 , mil . en . length / 2 ) ;
167
+ mil . n = mil . en . slice ( - mil . en . length / 2 ) ;
168
+ mgrsGridRef = `${ mil . gzd } ${ mil . en100k } ${ mil . e } ${ mil . n } ` ;
163
169
}
164
170
165
171
// match separate elements (separated by whitespace)
@@ -168,9 +174,9 @@ class Mgrs {
168
174
if ( ref == null || ref . length != 4 ) throw new Error ( `invalid MGRS grid reference ‘${ mgrsGridRef } ’` ) ;
169
175
170
176
// split gzd into zone/band
171
- const gzd = ref [ 0 ] ;
172
- const zone = gzd . slice ( 0 , 2 ) ;
173
- const band = gzd . slice ( 2 , 3 ) ;
177
+ const gzd = ref [ 0 ] . match ( / ( \d \d ? ) ( [ A - Z ] ) / i ) ;
178
+ const zone = gzd [ 1 ] ;
179
+ const band = gzd [ 2 ] ;
174
180
175
181
// split 100km letter-pair into e/n
176
182
const en100k = ref [ 1 ] ;
0 commit comments