-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathadd-query-args.js
42 lines (37 loc) · 1.3 KB
/
add-query-args.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
/**
* Internal dependencies
*/
import { getQueryArgs } from './get-query-args';
import { buildQueryString } from './build-query-string';
/**
* Appends arguments as querystring to the provided URL. If the URL already
* includes query arguments, the arguments are merged with (and take precedent
* over) the existing set.
*
* @param {string} [url=''] URL to which arguments should be appended. If omitted,
* only the resulting querystring is returned.
* @param {Object} [args] Query arguments to apply to URL.
*
* @example
* ```js
* const newURL = addQueryArgs( 'https://google.com', { q: 'test' } ); // https://google.com/?q=test
* ```
*
* @return {string} URL with arguments applied.
*/
export function addQueryArgs( url = '', args ) {
// If no arguments are to be appended, return original URL.
if ( ! args || ! Object.keys( args ).length ) {
return url;
}
let baseUrl = url;
// Determine whether URL already had query arguments.
const queryStringIndex = url.indexOf( '?' );
if ( queryStringIndex !== -1 ) {
// Merge into existing query arguments.
args = Object.assign( getQueryArgs( url ), args );
// Change working base URL to omit previous query arguments.
baseUrl = baseUrl.substr( 0, queryStringIndex );
}
return baseUrl + '?' + buildQueryString( args );
}