@bigfishtv/cockpit
Version:
68 lines (60 loc) • 1.83 kB
JavaScript
import queryString from 'query-string'
/**
* URL Utilities
* @module Utilities/urlUtils
*/
/**
* Replaces relative urls with absolute ones. Supports src and href attributes.
*
* @param {String} html
* @param {String} baseUrl = window.location.origin
* @return {String}
*/
export function htmlToAbsoluteUrls(html, baseUrl = window.location.origin) {
return html.replace(/(src|href)=(["'])(\/[^"']*)/gi, '$1=$2' + baseUrl + '$3')
}
/**
* Converts a relative url to absolute, ignores if provided an absolute url
* @param {String} url Relative url
* @param {String} baseUrl Defaults to window.location.origin
* @return {String}
*/
export function toAbsoluteUrl(url, baseUrl = window.location.origin) {
if (!url.match(/((http|https|ftp):\/\/)/gi) && url.charAt(0) == '/') return baseUrl + url
return url
}
/**
* Converts an absolute url to relative, ignores if provided an absolute url
* @param {String} url Absolute url
* @return {String}
*/
export function toRelativeUrl(url) {
const regex = /(http|https|ftp):\/\/([\-_A-z0-9\.]*)((:\d){2,4})?(.*)/gi
if (!url.match(regex)) return url
return url.replace(regex, '$5')
}
const defaultConfig = { arrayFormat: 'bracket' }
/**
* Parse a query string into an object. Uses query-string package
*
* eg. parseQuery('?page=1') -> { page: 1 }
*
* @param {string} query
* @param {object} config
* @return {object}
*/
export function parseQuery(query, config = defaultConfig) {
return queryString.parse(query, config)
}
/**
* Creates a query string from an object. Uses query-string package
*
* eg. stringifyQuery({ page: 1 }) -> 'page=1'
*
* @param {object} queryObj
* @param {object} config
* @return {string}
*/
export function stringifyQuery(queryObj, config = defaultConfig) {
return queryString.stringify(queryObj, config)
}