-
Notifications
You must be signed in to change notification settings - Fork 20
/
Url.js
1097 lines (903 loc) · 50 KB
/
Url.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*______________
| ______ | U I Z E J A V A S C R I P T F R A M E W O R K
| / / | ---------------------------------------------------
| / O / | MODULE : Uize.Url Package
| / / / |
| / / / /| | ONLINE : http://www.uize.com
| /____/ /__/_| | COPYRIGHT : (c)2004-2016 UIZE
| /___ | LICENSE : Available under MIT License or GNU General Public License
|_______________| http://www.uize.com/license.html
*/
/* Module Meta Data
type: Package
importance: 7
codeCompleteness: 100
docCompleteness: 100
*/
/*?
Introduction
The =Uize.Url= module eases working with URLs, supporting query string parsing and serialization, resolving relative URLs to absolute URLs, and more.
*DEVELOPERS:* `Chris van Rensburg`
*/
Uize.module ({
name:'Uize.Url',
builder:function () {
'use strict';
var
/*** Variables for Scruncher Optimization ***/
_undefined,
_isArray = Uize.isArray,
/*** references to static methods used internally ***/
_from,
_fromParams,
_toParams,
_fromPiece,
_toPiece,
/*** General Variables ***/
_sacredEmptyArray = [],
_sacredEmptyObject = {},
_cacheDefeatStrCallCount = 0,
_paramsDecodingOptionsDontFavorQuery = {favorQuery:false},
_leadingBackFoldersRegExp = /^(\.\.\/)*/
;
/*** Utility Functions ***/
function _splitOnQuery (_url,_favorQuery) {
var _queryPos = (_url += '').indexOf ('?');
if (_queryPos < 0 && !_favorQuery) _queryPos = _url.length;
return {
_urlPath:_url.slice (0,_queryPos),
_queryStr:_url.slice (_queryPos + 1)
};
}
return Uize.package ({
from:_from = function (_urlStr) {
var _urlSegmentsMatch =
_urlStr &&
_urlStr.match (
/^(([^:\\\/]+:)\/\/(([^:\\\/]*)(:(\d+))?)?)?(([^\?#]*[\\\/])?(([^\\\/\?#]*?)(\.([^\.\?#]+))?))(\?([^#]*))?(#(.*))?$/
)
;
function _getUrlSegment (_segmentNo) {
return _urlSegmentsMatch ? (_urlSegmentsMatch [_segmentNo] || '') : '';
}
return { // * properties marked '*' are consistent with browser's location object
href:_urlStr, // * eg. http://uize.com:80/reference/Uize.html?param=value#anchor
fullDomain:_getUrlSegment (1), // eg. http://uize.com:80
protocol:_getUrlSegment (2), // * eg. http:
host:_getUrlSegment (3), // * eg. uize.com:80
hostname:_getUrlSegment (4), // * eg. uize.com
port:_getUrlSegment (6), // * eg. 80
pathname:_getUrlSegment (7), // * eg. /reference/Uize.html
folderPath:_getUrlSegment (8), // eg. /reference/
file:_getUrlSegment (9), // eg. Uize.html
fileName:_getUrlSegment (10), // eg. Uize
extension:_getUrlSegment (11), // eg. .html
fileType:_getUrlSegment (12), // eg. html
search:_getUrlSegment (13), // * eg. ?param=value
query:_getUrlSegment (14), // eg. param=value
hash:_getUrlSegment (15), // * eg. #anchor
anchor:_getUrlSegment (16) // eg. hash
};
/*?
Static Methods
Uize.Url.from
Returns an object, containing properties for the various logical segments of the specified URL string.
SYNTAX
........................................
urlSegmentsOBJ = Uize.Url.from (urlSTR);
........................................
This method provides a convenient way to get at very precise portions of a URL string, such as the file name without the extension, the file type without the "." (period) character, the query params string without the "?" (question mark) character, the anchor without the "#" (pound / hash) character, etc.
URL Segment Properties
The =urlSegmentsOBJ= object returned by this method has the following structure...
URL SEGMENTS OBJECT
............................................................................................
{
href : hrefSTR, // http://uize.com:80/reference/Uize.html?param=value#anchor
fullDomain : fullDomainSTR, // http://uize.com:80
protocol : protocolSTR, // http:
host : hostSTR, // uize.com:80
hostname : hostnameSTR, // uize.com
port : portSTR, // 80
pathname : pathnameSTR, // /reference/Uize.html
folderPath : folderPathSTR, // /reference/
file : fileSTR, // Uize.html
fileName : fileNameSTR, // Uize
extension : extensionSTR, // .html
fileType : fileTypeSTR, // html
search : searchSTR, // ?param=value
query : querySTR, // param=value
hash : hashSTR, // #anchor
anchor : anchorSTR // hash
}
............................................................................................
The URL segment properties are described in more detail below...
href
A string, representing the entire URL string parsed by the =Uize.Url.from= method.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<----------------------------------------------------->|
VALUE : http://uize.com:80/reference/Uize.html?param=value#anchor
.....................................................................
NOTES
- this property is equivalent to the same named property of the =window.location= object (see `Properties Consistent with window.location`)
fullDomain
A string, representing the portion of the URL comprised of the =protocol=, "//" (two forward slashes), and the =host=.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<-------------->|
VALUE : http://uize.com:80
.....................................................................
NOTES
- for relative URLs that only specify a =pathname= and/or =search= and/or =hash=, the value of this property will be =''= (an empty string)
protocol
A string, representing the [[http://en.wikipedia.org/wiki/Internet_Protocol][Internet protocol]] in use by the URL (e.g. =http=, =ftp=, =irc=, =ssh=, etc.)
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<->|
VALUE : http:
.....................................................................
NOTES
- for relative URLs that only specify a =pathname= and/or =search= and/or =hash=, the value of this property will be =''= (an empty string)
- this property is equivalent to the same named property of the =window.location= object (see `Properties Consistent with window.location`)
host
A string, representing the portion of the URL comprised of the =hostname=, followed by a ":" (colon) character and the =port= if a port is present in the URL.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<------->|
VALUE : uize.com:80
.....................................................................
NOTES
- for relative URLs that only specify a =pathname= and/or =search= and/or =hash=, the value of this property will be =''= (an empty string)
- this property is equivalent to the same named property of the =window.location= object (see `Properties Consistent with window.location`)
hostname
A string, representing the portion of the URL comprised of just the name of the host (i.e. domain name or IP address) and without the =protocol= and =port= portions.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<---->|
VALUE : uize.com
.....................................................................
NOTES
- for relative URLs that only specify a =pathname= and/or =search= and/or =hash=, the value of this property will be =''= (an empty string)
- this property is equivalent to the same named property of the =window.location= object (see `Properties Consistent with window.location`)
port
A string, representing the portion of the URL that specifies the [[http://en.wikipedia.org/wiki/TCP_and_UDP_port][port]] on which to communicate with a server.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : ^^
VALUE : 80
.....................................................................
Most URLs will not contain an explicit port, and the port will typically be defaulted by the server to 80 for communication via HTTP, and 443 for secure communication via HTTPS. For URLs that do not specify a port, the value of the =port= property will be =''= (an empty string).
NOTES
- for relative URLs that only specify a =pathname= and/or =search= and/or =hash=, the value of this property will be =''= (an empty string)
- this property is equivalent to the same named property of the =window.location= object (see `Properties Consistent with window.location`)
pathname
A string, representing the portion of the URL comprised of the =folderPath= and =file=, and excluding the =fullDomain=, =search=, and =hash=.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<---------------->|
VALUE : /reference/Uize.html
.....................................................................
NOTES
- this property is equivalent to the same named property of the =window.location= object (see `Properties Consistent with window.location`)
folderPath
A string, representing the complete path to a folder (which may include multiple nested folder levels), and excluding the =fullDomain=, =file=, =search=, and =hash=.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<------->|
VALUE : /reference/
.....................................................................
file
A string, representing the portion of the URL comprised of just the =fileName= and =extension=, and excluding the =fullDomain=, =folderPath=, =search=, and =hash=.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<----->|
VALUE : Uize.html
.....................................................................
fileName
A string, representing the portion of the URL that specifies just the file name for a file, and excluding its =extension=.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<>|
VALUE : Uize
.....................................................................
extension
A string, representing the portion of the URL that specifies just the file extension for a file, and excluding its =fileName=.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<->|
VALUE : .html
.....................................................................
Unlike the =fileType= property, the =extension= property contains the conventional "." (period character) delimiter that separates the =fileName= and =fileType=.
fileType
A string, representing the portion of the URL that specifies just the file type for a file, and excluding the conventional "." (period character) delimiter that separates the =fileName= and =fileType=.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<>|
VALUE : html
.....................................................................
search
A string, representing the portion of the URL comprised of the "?" (question mark) character and =query=, if present in the URL.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<-------->|
VALUE : ?param=value
.....................................................................
Unlike the =query= property, the =search= property contains the conventional "?" (question mark character) that delimits the =query= from preceding portions of the URL.
NOTES
- this property is equivalent to the same named property of the =window.location= object (see `Properties Consistent with window.location`)
query
A string, representing the portion of the URL that specifies just the query parameters, and excluding the conventional "?" (question mark character) that delimits the =query= from preceding portions of the URL.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<------->|
VALUE : param=value
.....................................................................
hash
A string, representing the portion of the URL comprised of the "#" (hash / pound) character and =anchor=, if present in the URL.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<--->|
VALUE : #anchor
.....................................................................
Unlike the =anchor= property, the =hash= property contains the conventional "#" (hash / pound character) that delimits the =anchor= from preceding portions of the URL.
NOTES
- this property is equivalent to the same named property of the =window.location= object (see `Properties Consistent with window.location`)
anchor
A string, representing the portion of the URL that specifies just the anchor name, and excluding the conventional "#" (hash / pound character) that delimits the =anchor= from preceding portions of the URL.
ILLUSTRATION
.....................................................................
URL : http://uize.com:80/reference/Uize.html?param=value#anchor
PORTION : |<-->|
VALUE : anchor
.....................................................................
Properties Consistent with window.location
Of the properties in the =urlSegmentsOBJ= object returned by the =Uize.Url.from= method, the properties =href=, =protocol=, =host=, =hostname=, =port=, =pathname=, =search=, and =hash= are consistent with the properties of the built-in =window.location= object.
URL Segments, as a Tree
The following diagram shows the properties of the =urlSegmentsOBJ= object as a tree structure, illustrating the relationship between the properties...
URL SEGMENTS, AS A TREE
........................
href
|__ fullDomain
| |__ protocol
| |__ //
| |__ host
| |__ hostname
| |__ :
| |__ port
|
|__ pathname
| |__ folderPath
| |__ file
| |__ fileName
| |__ extension
| |__ .
| |__ fileType
|
|__ search
| |__ ?
| |__ query
|
|__ hash
|__ #
|__ anchor
........................
Reconstructing a URL String
A URL string can be reconstructed from a =urlSegmentsOBJ= type value in one of the following ways...
...........................
urlStr =
urlSegments.fullDomain +
urlSegments.pathname +
urlSegments.search +
urlSegments.hash
;
urlStr =
urlSegments.fullDomain +
urlSegments.folderPath +
urlSegments.file +
urlSegments.search +
urlSegments.hash
;
urlStr =
urlSegments.fullDomain +
urlSegments.folderPath +
urlSegments.fileName +
urlSegments.extension +
urlSegments.search +
urlSegments.hash
;
...........................
If you wish to reconstruct a URL string using any of the more granular URL segment properties, such as =protocol=, =hostname=, =port=, =fileType=, =query=, etc., then you will have to use logic to conditionally include the delimiters =//=, =:=, =.=, =?=, and =#=.
NOTES
- see also the =Uize.Url.fromParams= and =Uize.Url.fromPiece= static methods
*/
},
fromParams:_fromParams = function (_urlParamsStr,_decodingOptions) {
var _urlParams = {};
if (
_urlParamsStr = _splitOnQuery (
_urlParamsStr,
(_decodingOptions || _sacredEmptyObject).favorQuery !== false
)._queryStr
) {
for (
var
_urlParamPairNo = -1,
_urlParamPairs = _urlParamsStr.split ('&'),
_urlParamPairsLength = _urlParamPairs.length,
_urlParamPair,
_urlParamNameEncoded
;
++_urlParamPairNo < _urlParamPairsLength;
) {
if (_urlParamNameEncoded = (_urlParamPair = _urlParamPairs [_urlParamPairNo].split ('=')) [0])
_urlParams [_fromPiece (_urlParamNameEncoded)] = _fromPiece (_urlParamPair [1])
;
}
}
return _urlParams;
/*?
Static Methods
Uize.Url.fromParams
A utility method that parses a query string and returns the query parameters as an object.
SYNTAX
.................................................
paramsOBJ = Uize.Url.fromParams (queryParamsSTR);
.................................................
This method assumes that the query string was serialized using "&" to separate parameters, and "=" to separate parameter name from parameter value in each name/value pair.
EXAMPLE
.............................................................
Uize.Url.fromParams ('category=holiday&type=all&results=20');
.............................................................
With the above query string, the =Uize.Url.fromParams= method would produce the object...
......................
{
category:'holiday',
type:'all',
results:'20'
}
......................
The value of the =queryParamsSTR= parameter may contain a prepended query '?' character, and even a URL path. These will simply be ignored when parsing the query parameters, so this method can be applied to a complete URL without worrying about first having to remove the path. So, extending on the above example, the same result would be produced if the value of the =queryParamsSTR= parameter was ='http://www.somedomain.com/search?category=holiday&type=all&results=20'=.
NOTES
- when parsing the query string, all parameter values are treated as strings
- see also the corresponding =Uize.Url.toParams= static method
*/
},
fromPiece:_fromPiece = function (_toDecode) {
return _toDecode != _undefined ? decodeURIComponent (_toDecode) : '';
/*?
Static Methods
Uize.Url.fromPiece
Returns a string, representing the decoded form of the specified URL segment string.
SYNTAX
.......................................................
unencodedSTR = Uize.Url.fromPiece (encodedUrlPieceSTR);
.......................................................
EXAMPLE
....................................................................................
unencoded = Uize.Url.fromPiece ('solar%2C%20wind%2C%20efficiency%20%26%20biofuels');
....................................................................................
After executing the above statement, the variable =unencoded= would have the value ='solar, wind, efficiency & biofuels'=.
NOTES
- see also the corresponding =Uize.Url.toPiece= static method
*/
},
getCacheDefeatStr:function () {
return Uize.now () + '' + Math.round (Math.random () * 1000) + _cacheDefeatStrCallCount++;
/*?
Static Methods
Uize.Url.getCacheDefeatStr
A utility method that returns a string value, generated using time and a random number, that can then be used as a uniquifying query parameter on request URLs in order to defeat client caching.
SYNTAX
...............................................
cacheDefeatSTR = Uize.Url.getCacheDefeatStr ();
...............................................
NOTES
- this method takes no parameters
*/
},
toRelative:function (_baseUrl,_urlToRelativize) {
if (!_baseUrl) {
return _urlToRelativize;
} else {
var _urlToRelativizeIsRootRelative = _urlToRelativize.charAt (0) == '/';
if (
_urlToRelativizeIsRootRelative == (_baseUrl.charAt (0) == '/') &&
// both URLs are root-relative, or both URLs are not root-relative
_urlToRelativize.match (_leadingBackFoldersRegExp) [0].length ==
_baseUrl.match (_leadingBackFoldersRegExp) [0].length &&
// both URLs have the same amount of back-relative jumps (or none)
_from (_urlToRelativize).fullDomain == _from (_baseUrl).fullDomain
// both URLs have the same full domain (or none)
) {
var
_result = '',
_commonStr = _baseUrl.slice (0,_baseUrl.lastIndexOf ('/') + 1),
_matchFound = false,
_slashPos
;
while (!_matchFound) {
if (!(_matchFound = _urlToRelativize.slice (0,_commonStr.length) == _commonStr)) {
_matchFound = (_slashPos = _commonStr.lastIndexOf ('/',_commonStr.length - 2)) < 0;
_result += '../';
_commonStr = _commonStr.slice (0,_slashPos + 1);
}
}
return _result + _urlToRelativize.slice (_commonStr.length);
} else {
return _from (_urlToRelativize).fullDomain ? _urlToRelativize : null;
}
}
/*?
Static Methods
Uize.Url.toRelative
Returns a string, representing a relative URL from the specified base URL to the specified destination URL.
SYNTAX
.....................................................................
relativeUrlSTR = Uize.Url.toRelative (baseUrlSTR,urlToRelativizeSTR);
.....................................................................
EXAMPLE
....................................................
var relativeUrl = Uize.Url.toRelative (
'http://www.somedomain.com/foo/bar/',
'http://www.somedomain.com/foo/baz/qux/file.html'
);
....................................................
RESULT
......................
'../baz/qux/file.html'
......................
When a Relative URL Can Be Created
The =Uize.Url.toRelative= method can create a relative URL in any case where the URL it would create, when applied against the specified base URL, would produce the original URL to relativize.
Situations in which a relative URL can be created include...
- `when both URLs have the same back-relative prefix`
- `when both URLs are root-relative`
- `when both URLs are forward-relative`
- `when both URLs have the same domain`
When Both URLs Have the Same Back-relative Prefix
When both the base URL and the URL to relativize start with exactly the same back-relative prefix (i.e. "/", "../", "../../", etc.), then a relative URL can be created.
Even though both URLs may be relative URLs, a relative URL can still be created between the base URL and the URL to relativize. This is because the URLs having the identical back-relative prefix means that they essentially share a common base, even though we don't know what it is.
EXAMPLE
.......................................
var relativeUrl = Uize.Url.toRelative (
'../../foo/bar/',
'../../foo/baz/qux/file.html'
);
.......................................
In the above example, both the base URL and the URL to relativize have a back-relative prefix that jumps back two folder levels.
RESULT
......................
'../baz/qux/file.html'
......................
When Both URLs are Root-relative
When both the base URL and the URL to relativize are root-relative (i.e. start with a "/"), then a relative URL can be created.
EXAMPLE
.......................................
var relativeUrl = Uize.Url.toRelative (
'/foo/bar/',
'/foo/baz/qux/file.html'
);
.......................................
RESULT
......................
'../baz/qux/file.html'
......................
When Both URLs are Forward-relative
When both the base URL and the URL to relativize are forward-relative, then a relative URL can be created.
EXAMPLE
.......................................
var relativeUrl = Uize.Url.toRelative (
'foo/bar/',
'foo/baz/qux/file.html'
);
.......................................
RESULT
......................
'../baz/qux/file.html'
......................
When Both URLs Have the Same Domain
When both the base URL and the URL to relativize have the same domain, then a relative URL can be created.
EXAMPLE
....................................................
var relativeUrl = Uize.Url.toRelative (
'http://www.somedomain.com/foo/bar/',
'http://www.somedomain.com/foo/baz/qux/file.html'
);
....................................................
RESULT
......................
'../baz/qux/file.html'
......................
When a Relative URL Cannot Be Created
In cases where it is impossible to create a relative URL (see `When a Relative URL Can Be Created`), the value =null= will be returned, unless the URL to relativize is an absolute URL, in which case the URL to relativize will be returned.
Whenever the base URL and the URL to relativize do not have the same shared base, then a relative URL cannot be created. This can occur when...
- the base URL is absolute (i.e. has a domain) and the URL to relativize is either root-relative, forward-relative, back-relative, or has a domain that doesn't match that of the base URL
- the base URL is root-relative and the URL to relativize is either forward-relative, back-relative, or is absolute (i.e. has a domain)
- the base URL is forward-relative and the URL to relativize is either root-relative, back-relative, or is absolute (i.e. has a domain)
- the base URL is back-relative and the URL to relativize is either root-relative, forward-relative, or is absolute (i.e. has a domain), or is also back-relative but has a differing amount of back folder jumps than the base URL
EXAMPLES
............................................................................................
// base URL is absolute (i.e. has a domain)
Uize.Url.toRelative ('http://www.foo.com/','/foo/bar/'); // null
Uize.Url.toRelative ('http://www.foo.com/','foo/bar/'); // null
Uize.Url.toRelative ('http://www.foo.com/','../foo/bar/'); // null
Uize.Url.toRelative ('http://www.foo.com/','http://www.bar.com/'); // 'http://www.bar.com/'
// base URL is root-relative
Uize.Url.toRelative ('/foo/bar/','foo/bar/'); // null
Uize.Url.toRelative ('/foo/bar/','../foo/bar/'); // null
Uize.Url.toRelative ('/foo/bar/','http://www.bar.com/'); // 'http://www.bar.com/'
// base URL is forward-relative
Uize.Url.toRelative ('foo/bar/','/foo/bar/'); // null
Uize.Url.toRelative ('foo/bar/','../foo/bar/'); // null
Uize.Url.toRelative ('foo/bar/','http://www.bar.com/'); // 'http://www.bar.com/'
// base URL is back-relative
Uize.Url.toRelative ('../foo/bar/','/foo/bar/'); // null
Uize.Url.toRelative ('../foo/bar/','foo/bar/'); // null
Uize.Url.toRelative ('../foo/bar/','../../foo/bar/'); // null
Uize.Url.toRelative ('../foo/bar/','http://www.bar.com/'); // 'http://www.bar.com/'
............................................................................................
When the URL to Relativize is Absolute
`When a relative URL cannot be created` and the URL to relativize is absolute (i.e. has a domain), then the URL to relativize will be returned rather than the value =null=.
The rationale behind this behavior is that an absolute URL, when resolved against another URL, will always produce that absolute URL. So, returning an absolute URL that can work against the base URL is better than returning =null=.
When the Base URL Contains a File Part
When the base URL contains a file part, that file part will be ignored and discarded when creating the relative URL.
This is a convenient behavior if you are using this method in a Web page to create relative URLs from absolute URLs, and where the created URLs should be relative to the current document's URL. In such cases, the value of the =window.location.href= property can simply be passed to the =Uize.Url.toRelative= method as the value of the =baseUrlSTR= parameter.
EXAMPLE
...................................................
var relativeUrl = Uize.Url.toRelative (
'http://www.somedomain.com/foo/bar/file.html',
'http://www.somedomain.com/foo/hello/world.html'
);
...................................................
RESULT
.....................
'../hello/world.html'
.....................
Because of this behavior, for any base URL that ends in a folder, the URL must also end with a "/" (slash) character, otherwise the last folder will be assumed to be a file part and will be discarded when creating the relative URL. The =Uize.Url.toRelative= method cannot tell the difference between a folder name and a filename that has no file extension (filename's are not required to have an extension indicating file type, after all, even though they often may).
NOTES
- see the related =Uize.Url.toAbsolute= static method
*/
},
toAbsolute:function (_baseUrl,_urlToAbsolutize) {
var _baseUrlPieces = _urlToAbsolutize ? _from (_urlToAbsolutize) : _sacredEmptyObject;
_baseUrlPieces.fullDomain ? (_urlToAbsolutize = '') : (_baseUrlPieces = _from (_baseUrl));
var
_lastFolderPathAndFilename,
_folderPathAndFilename = _baseUrlPieces.folderPath + _urlToAbsolutize
;
while (_folderPathAndFilename != _lastFolderPathAndFilename) {
_lastFolderPathAndFilename = _folderPathAndFilename;
_folderPathAndFilename = _folderPathAndFilename.replace (/([\/\\])[^\/\\]*[\/\\]\.\.(?:[\/\\]|$)/,'$1');
}
return _baseUrlPieces.fullDomain + _folderPathAndFilename.replace (/\.\.([\/\\]|$)/g,'');
/*?
Static Methods
Uize.Url.toAbsolute
Returns a string, representing the specified relative URL resolved against the specified base URL.
SYNTAX
.....................................................................
absoluteUrlSTR = Uize.Url.toAbsolute (baseUrlSTR,urlToAbsolutizeSTR);
.....................................................................
EXAMPLE 1
.........................................................
Uize.Url.toAbsolute (
'http://www.uize.com/reference/source-code/Uize.html',
'../../download.html'
);
.........................................................
The above statement would produce the value ='http://www.uize.com/download.html'=.
EXAMPLE 2
.......................................................................
Uize.Url.toAbsolute ('http://www.uize.com/index.html','download.html');
.......................................................................
The above statement would produce the value ='http://www.uize.com/download.html'=.
EXAMPLE 3
..........................................................
Uize.Url.toAbsolute ('http://www.uize.com/index.html','');
..........................................................
The above statement would produce the value ='http://www.uize.com'=.
NOTES
- see the related =Uize.Url.toAbsolute= static method
*/
},
toParams:_toParams = function (_urlParams) {
var
_urlParamPairs = [],
_paramValue
;
if (_isArray (_urlParams))
_urlParams = _urlParams.length < 2
? _urlParams [0]
: Uize.copyInto.apply (Uize,[{}].concat (_urlParams))
;
for (var _paramName in _urlParams)
_paramName && (_paramValue = _urlParams [_paramName]) != _undefined &&
_urlParamPairs.push (_toPiece (_paramName) + '=' + _toPiece (_paramValue))
;
return _urlParamPairs.join ('&');
/*?
Static Methods
Uize.Url.toParams
A utility method that serializes the properties of the specified object to produce a URL query params string.
SYNTAX
...............................................
queryParamsSTR = Uize.Url.toParams (paramsOBJ);
...............................................
This method assumes that the params in =paramsOBJ= should be serialized using "&" to separate parameters, and "=" to separate parameter name from parameter value in each name/value pair.
EXAMPLE
......................
Uize.Url.toParams ({
category:'holiday',
type:'all',
results:'20'
});
......................
With the above =paramsOBJ= value, the =Uize.Url.toParams= method would produce the string...
......................................
'category=holiday&type=all&results=20'
......................................
VARIATION
...........................................................
queryParamsSTR = Uize.Url.toParams (urlParamsObjectsARRAY);
...........................................................
When a =urlParamsObjectsARRAY= parameter is specified, multiple params objects can be specified in an array. This provides for an easy way to merge query param sets from multiple sources, or to blend fixed params with parameterized params (e.g. passed in a method call), or to override the values in param sets. The values from params objects later in the array override those from earlier params objects. None of the objects in the array will be modified by the operation.
EXAMPLE
..............................................................
var defaultSearchSettings = {
sort:'recent',
type:'all',
results:'20'
};
searchQueryParamsStr = Uize.Url.toParams (
[defaultSearchSettings,{category:'holiday',sort:'popular'}]
);
..............................................................
In the above example, the values of the =category= and =sort= properties of the second params object in the =urlParamsObjectsARRAY= value would be stitched in to the values provided by the =defaultSearchSettings= query params object that appears first in the array, with the value of the =sort= property of the second params object overriding the value contained in the =defaultSearchSettings= object, and with the =defaultSearchSettings= object *not* being modified in the process.
NOTES
- this method does not prepend the query '?' character to the params string
- see also the corresponding =Uize.Url.fromParams= static method
*/
},
toPiece:_toPiece = function _encodeUrlPiece (_toEncode) {
return encodeURIComponent (_toEncode + '');
/*?
Static Methods
Uize.Url.toPiece
Returns a string, representing the URL encoded form of the specified string.
SYNTAX
.....................................................
encodedUrlPieceSTR = Uize.Url.toPiece (unencodedSTR);
.....................................................
EXAMPLE
..........................................................................
encodedUrlPiece = Uize.Url.toPiece ('solar, wind, efficiency & biofuels');
..........................................................................
After executing the above statement, the variable =encodedUrlPiece= would have the value ='solar%2C%20wind%2C%20efficiency%20%26%20biofuels'=.
NOTES
- see also the corresponding =Uize.Url.fromPiece= static method
*/
},
resolve:function (_url,_urlParams) {
if (_url == _undefined) _url = '';
if (_isArray (_url)) {
_urlParams = _url.slice (1).concat (_urlParams || _sacredEmptyArray);
_url = _url [0];
}
var _urlParamsStr = _toParams (
[_fromParams (_url,_paramsDecodingOptionsDontFavorQuery)].concat (
_isArray (_urlParams) ? _urlParams : [_urlParams]
)
);
return _splitOnQuery (_url)._urlPath + (_urlParamsStr ? '?' : '') + _urlParamsStr;
/*?
Static Methods
Uize.Url.resolve
Returns a string, representing a URL that has been resolved from the specified URL path string and query params object.
SYNTAX
....................................................
urlSTR = Uize.Url.resolve (urlPathSTR,urlParamsOBJ);
....................................................
EXAMPLE
......................................
searchUrl = Uize.Url.resolve (
'http://www.somedomain.com/search',
{
category:'holiday',
type:'all',
results:'20'
}
);
......................................
In the above example, the =Uize.Url.resolve= method would produce the result ='http://www.somedomain.com/search?category=holiday&type=all&results=20'=.
An Existing Query Character
The value of the =urlPathSTR= parameter may already contain a query '?' character at the end.
If this is the case, the =Uize.Url.resolve= method will *not* add an additional query character. So, the following example would produce the same result as the first example...
EXAMPLE
.......................................
searchUrl = Uize.Url.resolve (
'http://www.somedomain.com/search?',
{
category:'holiday',
type:'all',
results:'20'
}
);
.......................................
In the above example, the =Uize.Url.resolve= method would produce the result ='http://www.somedomain.com/search?category=holiday&type=all&results=20'=.
Augmenting Existing Query Params
The value of the =urlPathSTR= parameter may already contain query parameters.
If this is the case, the =Uize.Url.resolve= method will concatenate the additional query parameters using the '&' query param delimiter.
EXAMPLE
..................................................
searchUrl = Uize.Url.resolve (
'http://www.somedomain.com/search?sort=recent',
{
category:'holiday',
type:'all',
results:'20'
}
);
..................................................
In the above example, the =Uize.Url.resolve= method would produce the result ='http://www.somedomain.com/search?sort=recent&category=holiday&type=all&results=20'=.
Modifying Existing Query Params
The value of the =urlPathSTR= parameter may contain query parameters whose values you wish to modify.
Overwriting existing values for query params is handled automatically by the =Uize.Url.resolve= method - all you have to do is specify the new values in the =urlParamsOBJ= parameter.
EXAMPLE
......................................................................
searchUrl = Uize.Url.resolve (
'http://www.somedomain.com/search?sort=recent&results=20',
{
sort:'popular', // overwrites existing sort param in URL
category:'holiday',
type:'all',
results:'100' // overwrites existing results param in URL
}
);
......................................................................
In the above example, the =Uize.Url.resolve= method would produce the result ='http://www.somedomain.com/search?sort=popular&results=100&category=holiday&type=all'=.
Removing Existing Query Params
The value of the =urlPathSTR= parameter may contain query parameters that you wish to remove.
Removing existing query params from a URL can be accomplished by specifying the value =null= for the params you wish to remove in the =urlParamsOBJ= parameter. You can specify to remove params that don't exist in the URL, without any ill effects - those params will simply be ignored.
EXAMPLE
..........................................................................
searchUrl = Uize.Url.resolve (
'http://www.somedomain.com/search?sort=recent&results=20',
{
sort:null, // removes existing sort param in URL
category:null, // would remove category param in URL, if it existed
type:'all',
results:null // removes existing results param in URL
}
);
..........................................................................
In the above example, the =Uize.Url.resolve= method would produce the result ='http://www.somedomain.com/search?type=all'=.
Variations
The =Uize.Url.resolve= method is quite versatile in its signature, with several variations that can come in handy under different circumstances.
VARIATION 1
.............................................................
urlSTR = Uize.Url.resolve (urlPathSTR,urlParamsObjectsARRAY);
.............................................................
When a =urlParamsObjectsARRAY= parameter is specified, multiple params objects can be specified in an array. This provides for an easy way to merge query param sets from multiple sources, or to blend fixed params with parameterized params (e.g. passed in a method call), or to override the values in param sets. The values from params objects later in the array override those from earlier params objects. None of the objects in the array will be modified by the operation.
EXAMPLE
......................................
var defaultSearchSettings = {
sort:'recent',
type:'all',
results:'20'
};
searchUrl = Uize.Url.resolve (
'http://www.somedomain.com/search',
[
defaultSearchSettings,
{
category:'holiday',
sort:'popular'
}
]
);
......................................
In the above example, the values of the =category= and =sort= properties of the second params object in the =urlParamsObjectsARRAY= value would be stitched in to the values provided by the =defaultSearchSettings= query params object that appears first in the array, with the value of the =sort= property of the second params object overriding the value contained in the =defaultSearchSettings= object, and with the =defaultSearchSettings= object *not* being modified in the process.
VARIATION 2
.........................................................
urlSTR = Uize.Url.resolve (urlPathAndParamsObjectsARRAY);
.........................................................
Another versatile variation allows a single =urlPathAndParamsObjectsARRAY= parameter to be specified, where the array specified by this parameter contains the URL path string as its first element, and an arbitrary number of params objects in subsequent elements. Using this variation, the example shown for *VARIATION 1* could be re-written as...
EXAMPLE
......................................