UNPKG

@bigfishtv/cockpit

Version:

75 lines (64 loc) 2.16 kB
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) { var baseUrl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 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) { var baseUrl = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 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) { var regex = /(http|https|ftp):\/\/([\-_A-z0-9\.]*)((:\d){2,4})?(.*)/gi; if (!url.match(regex)) return url; return url.replace(regex, '$5'); } var 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) { var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 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) { var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : defaultConfig; return queryString.stringify(queryObj, config); }