UNPKG

@gravityforms/utils

Version:
54 lines (49 loc) 1.55 kB
/** * @module updateQueryVar * @description Modify a URL string's query args, by either adding a new one, updating an existing one, * or removing an existing one. * * @since 1.0.0 * * @param {string} key The URL param key. * @param {string|null} value The value for the key. Set to null to remove query arg. * @param {string} url An URL string to manipulate. Defaults to current. * * @return {string} Returns the updated URL. * * @example * import { updateQueryVar } from "@gravityforms/utils"; * * function Example() { * const url = 'http://domain.com/?query1=val1'; * const newUrl = updateQueryVar( 'query2', 'val2', url ); * } * */ export default function updateQueryVar( key, value, url = window.location.href ) { const separator = '?'; const hashSplit = url.split( '#' ); const hash = hashSplit[ 1 ] ? `#${ hashSplit[ 1 ] }` : ''; const querySplit = hashSplit[ 0 ].split( '?' ); const host = querySplit[ 0 ]; const query = querySplit[ 1 ]; const params = query !== undefined ? query.split( '&' ) : []; let updated = false; params.forEach( ( item, index ) => { if ( item.startsWith( `${ key }=` ) ) { updated = true; if ( ! value ) { // value is null, remove query arg params.splice( index, 1 ); } else { // update query arg params[ index ] = `${ key }=${ value }`; } } } ); if ( ! updated && value ) { // this is a new arg to add params[ params.length ] = `${ key }=${ value }`; } return `${ host }${ separator }${ params.join( '&' ) }${ hash }`; }