我分享我的解决方案,因为它支持相对URL和绝对URL。除此之外,它与顶部答案中使用的Web API相同。
export const setQueryParam = (url, key, value) => {
const dummyBaseUrl = 'https://dummy-base-url.com';
const result = new URL(url, dummyBaseUrl);
result.searchParams.set(key, value);
return result.toString().replace(dummyBaseUrl, '');
};
还有一些 Jest 测试:
describe('setQueryParams', () => {
it('sets param on relative url with base path', () => {
const actual = setQueryParam(
'/', 'ref', 'some-value',
);
expect(actual).toEqual('/?ref=some-value');
});
it('sets param on relative url with no path', () => {
const actual = setQueryParam(
'', 'ref', 'some-value',
);
expect(actual).toEqual('/?ref=some-value');
});
it('sets param on relative url with some path', () => {
const actual = setQueryParam(
'/some-path', 'ref', 'some-value',
);
expect(actual).toEqual('/some-path?ref=some-value');
});
it('overwrites existing param', () => {
const actual = setQueryParam(
'/?ref=prev-value', 'ref', 'some-value',
);
expect(actual).toEqual('/?ref=some-value');
});
it('sets param while another param exists', () => {
const actual = setQueryParam(
'/?other-param=other-value', 'ref', 'some-value',
);
expect(actual).toEqual('/?other-param=other-value&ref=some-value');
});
it('honors existing base url', () => {
const actual = setQueryParam(
'https://base.com', 'ref', 'some-value',
);
expect(actual).toEqual('https://base.com/?ref=some-value');
});
it('honors existing base url with some path', () => {
const actual = setQueryParam(
'https://base.com/some-path', 'ref', 'some-value',
);
expect(actual).toEqual('https://base.com/some-path?ref=some-value');
});
});