Skip to content

Commit e62360d

Browse files
authored
Normalize hash and search strings (#813) (#891)
1 parent 23c37fb commit e62360d

File tree

2 files changed

+67
-1
lines changed

2 files changed

+67
-1
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import expect from 'expect';
2+
import { createPath } from 'history';
3+
4+
describe('createPath', () => {
5+
describe('given only a pathname', () => {
6+
it('returns the pathname unchanged', () => {
7+
let path = createPath({ pathname: 'https://google.com' });
8+
expect(path).toBe('https://google.com');
9+
});
10+
});
11+
12+
describe('given a pathname and a search param', () => {
13+
it('returns the constructed pathname', () => {
14+
let path = createPath({
15+
pathname: 'https://google.com',
16+
search: '?something=cool'
17+
});
18+
expect(path).toBe('https://google.com?something=cool');
19+
});
20+
});
21+
22+
describe('given a pathname and a search param without ?', () => {
23+
it('returns the constructed pathname', () => {
24+
let path = createPath({
25+
pathname: 'https://google.com',
26+
search: 'something=cool'
27+
});
28+
expect(path).toBe('https://google.com?something=cool');
29+
});
30+
});
31+
32+
describe('given a pathname and a hash param', () => {
33+
it('returns the constructed pathname', () => {
34+
let path = createPath({
35+
pathname: 'https://google.com',
36+
hash: '#section-1'
37+
});
38+
expect(path).toBe('https://google.com#section-1');
39+
});
40+
});
41+
42+
describe('given a pathname and a hash param without #', () => {
43+
it('returns the constructed pathname', () => {
44+
let path = createPath({
45+
pathname: 'https://google.com',
46+
hash: 'section-1'
47+
});
48+
expect(path).toBe('https://google.com#section-1');
49+
});
50+
});
51+
52+
describe('given a full location object', () => {
53+
it('returns the constructed pathname', () => {
54+
let path = createPath({
55+
pathname: 'https://google.com',
56+
search: 'something=cool',
57+
hash: '#section-1'
58+
});
59+
expect(path).toBe('https://google.com?something=cool#section-1');
60+
});
61+
});
62+
});

packages/history/index.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1042,7 +1042,11 @@ export function createPath({
10421042
search = '',
10431043
hash = ''
10441044
}: PartialPath) {
1045-
return pathname + search + hash;
1045+
if (search && search !== '?')
1046+
pathname += search.charAt(0) === '?' ? search : '?' + search;
1047+
if (hash && hash !== '#')
1048+
pathname += hash.charAt(0) === '#' ? hash : '#' + hash;
1049+
return pathname;
10461050
}
10471051

10481052
/**

0 commit comments

Comments
 (0)