Skip to content

Commit

Permalink
URL: Avoid modifying input URL without any querystring
Browse files Browse the repository at this point in the history
  • Loading branch information
aduth committed Mar 13, 2020
1 parent 1c8921a commit e5e0f60
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 5 deletions.
11 changes: 6 additions & 5 deletions packages/url/src/remove-query-args.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ import { buildQueryString } from './build-query-string';
*/
export function removeQueryArgs( url, ...args ) {
const queryStringIndex = url.indexOf( '?' );
const query = getQueryArgs( url );
const baseUrl =
queryStringIndex !== -1 ? url.substr( 0, queryStringIndex ) : url;
if ( queryStringIndex === -1 ) {
return url;
}

const query = getQueryArgs( url );
const baseURL = url.substr( 0, queryStringIndex );
args.forEach( ( arg ) => delete query[ arg ] );

return baseUrl + '?' + buildQueryString( query );
return baseURL + '?' + buildQueryString( query );
}
6 changes: 6 additions & 0 deletions packages/url/src/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,12 @@ describe( 'hasQueryArg', () => {
} );

describe( 'removeQueryArgs', () => {
it( 'should not change URL without a querystring', () => {
const url = 'https://andalouses.example/beach';

expect( removeQueryArgs( url, 'baz', 'test' ) ).toEqual( url );
} );

it( 'should not change URL not containing query args', () => {
const url = 'https://andalouses.example/beach?foo=bar&bar=baz';

Expand Down

0 comments on commit e5e0f60

Please sign in to comment.