import { Injectable } from '../decorators' @Injectable('urlModificationService') export default class UrlModificationService { // http://stackoverflow.com/questions/5999118/add-or-update-query-string-parameter updateQueryStringParameter(uri: string, key: string, value: string): string { // construct a regex for the desired key consisting of the possible prefix character (? or &), // the key itself, the = and value, up to whichever separator character may exist (& # or $) or the end const re = new RegExp('([?&])' + key + '=.*?(&|#|$)', 'i') if (uri.match(re)) { // if the regex is found in the uri, then replace to update the value return uri.replace(re, '$1' + key + '=' + value + '$2') } else { // if the regex is not found in the uri // first, check for the presence of a hash in the uri and adjust if needed let hash = '' if ( uri.indexOf('#') !== -1 ) { hash = uri.replace(/.*#/, '#') uri = uri.replace(/#.*/, '') } // determine which parameter prefix character to use const separator = uri.indexOf('?') !== -1 ? '&' : '?' // and append the key and value return uri + separator + key + '=' + value + hash } } }