Skip to content

Instantly share code, notes, and snippets.

@radist2s
Last active September 5, 2017 11:25
Show Gist options
  • Save radist2s/7830209 to your computer and use it in GitHub Desktop.
Save radist2s/7830209 to your computer and use it in GitHub Desktop.
Javascript Simple url creator. Trim slashes.
var site_url = window.site_url,
site_path = window.site_path
var escapeRegExp = function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
/**
* @param {boolean} [leftTrim]
* @param {boolean} [rightTrim]
* @returns {string}
*/
String.prototype.trimSlash = function trimSlash(leftTrim, rightTrim){
var trimmerPatterns = []
if (leftTrim === undefined || leftTrim){
trimmerPatterns.push('^\/+')
}
if (rightTrim === undefined || rightTrim){
trimmerPatterns.push('\/+$')
}
var trimmer = new RegExp(trimmerPatterns.join('|'), 'g')
return this.replace(trimmer, '')
}
/**
* @param [url]
* @returns {string}
*/
String.prototype.getUrlPath = function getUrlPath(url){
url = url || this
return url.replace(new RegExp(escapeRegExp(site_url), 'i'), '').replace(/#.*/g, '').trimSlash(false, true)
}
/**
* @param [url]
* @returns {string}
*/
String.prototype.getUrlPathSimple = function getUrlPath(url){
if (!typeof url === 'string') {
throw new Error('url is not a string')
}
return url.substring(0, url.lastIndexOf('/')).trimSlash(false, true)
};
/**
* @param [url]
* @returns {string}
*/
var getUrlFile = function getUrlPath(url){
if (!isString(url)) {
throw new Error('url is not a string')
}
return url.substring(url.lastIndexOf('/')).trimSlash(true, true)
};
/**
* @param {string|string[]}[uri]
* @returns {string}
*/
String.prototype.createUrl = function createUrl(uri){
if (uri instanceof Array){
/** @var {Array} uri */
uri = uri.join('/')
}
uri = uri ? String(uri) : ''
var site_url_base = site_url.trimSlash(false, true)
var url_path = this.trimSlash() + (uri ? '/' + uri.trimSlash() : '')
return site_url_base + '/' + url_path.trimSlash()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment