Last active
September 5, 2017 11:25
-
-
Save radist2s/7830209 to your computer and use it in GitHub Desktop.
Javascript Simple url creator. Trim slashes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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