File tree Expand file tree Collapse file tree 2 files changed +29
-10
lines changed Expand file tree Collapse file tree 2 files changed +29
-10
lines changed Original file line number Diff line number Diff line change 3
3
const { parse, format } = require ( 'url' ) ;
4
4
5
5
function encodeURL ( str ) {
6
- if ( parse ( str ) . protocol ) {
6
+ const parsed = parse ( str ) ;
7
+ if ( parsed . protocol ) {
7
8
const obj = Object . assign ( { } , {
8
- auth : parse ( str ) . auth ,
9
- protocol : parse ( str ) . protocol ,
10
- host : parse ( str ) . host ,
11
- pathname : encodeURI ( decodeURI ( parse ( str ) . pathname ) )
9
+ auth : parsed . auth ,
10
+ protocol : parsed . protocol ,
11
+ host : parsed . host ,
12
+ pathname : encodeURI ( safeDecodeURI ( parsed . pathname ) )
12
13
} ) ;
13
14
14
- if ( parse ( str ) . hash ) {
15
- Object . assign ( obj , { hash : encodeURI ( decodeURI ( parse ( str ) . hash ) ) } ) ;
15
+ if ( parsed . hash ) {
16
+ Object . assign ( obj , { hash : encodeURI ( safeDecodeURI ( parsed . hash ) ) } ) ;
16
17
}
17
18
18
- if ( parse ( str ) . search ) {
19
- Object . assign ( obj , { search : encodeURI ( decodeURI ( parse ( str ) . search ) ) } ) ;
19
+ if ( parsed . search ) {
20
+ Object . assign ( obj , { search : encodeURI ( safeDecodeURI ( parsed . search ) ) } ) ;
20
21
}
21
22
22
23
return format ( obj ) ;
23
24
}
24
25
25
- return encodeURI ( decodeURI ( str ) ) ;
26
+ return encodeURI ( safeDecodeURI ( str ) ) ;
27
+ }
28
+
29
+ function safeDecodeURI ( str ) {
30
+ try {
31
+ return decodeURI ( str ) ;
32
+ } catch ( err ) {
33
+ return str ;
34
+ }
26
35
}
27
36
28
37
module . exports = encodeURL ;
Original file line number Diff line number Diff line change @@ -45,6 +45,16 @@ describe('encodeURL', () => {
45
45
encodeURL ( content ) . should . eql ( 'http://foo.com/bar?q%C3%BAery=b%C3%A1z' ) ;
46
46
} ) ;
47
47
48
+ it ( 'query contains %' , ( ) => {
49
+ const content = 'http://foo.com/bar?query=%' ;
50
+ encodeURL ( content ) . should . eql ( 'http://foo.com/bar?query=%25' ) ;
51
+ } ) ;
52
+
53
+ it ( 'path or query contains %' , ( ) => {
54
+ const content = '/bar?query=%' ;
55
+ encodeURL ( content ) . should . eql ( '/bar?query=%25' ) ;
56
+ } ) ;
57
+
48
58
it ( 'multiple queries' , ( ) => {
49
59
const content = 'http://foo.com/bar?query1=aáa&query2=aàa' ;
50
60
encodeURL ( content ) . should . eql ( 'http://foo.com/bar?query1=a%C3%A1a&query2=a%C3%A0a' ) ;
You can’t perform that action at this time.
0 commit comments