Skip to content

Instantly share code, notes, and snippets.

@pantoniotti
Last active December 18, 2015 00:19
Show Gist options
  • Save pantoniotti/5695639 to your computer and use it in GitHub Desktop.
Save pantoniotti/5695639 to your computer and use it in GitHub Desktop.
Bunch of userfull Url related methods in a coffeescript class
# Url Class
class @Url
constructor: (@path) ->
getQueryValue: (key) ->
try
queries = @getAllQueries()
i = 0
if queries && queries.length > 0
while i < queries.length
query = queries[i]
return query[1] if query[0] is key
i++
catch error
alert error.message
getAllQueries: ->
try
queries = []
values = new Array()
url = window.location.href
values = url.split(/[\?&]+/)
i = 1
if values && values.length > 0
while i < values.length
value = values[i].split("=")
queries.push(value)
i++
return queries
catch error
alert error.message
getPath: (index) ->
path = ""
try
path = window.location.pathname.substring(1)
path = path.split("/")[index] if path.indexOf("/") > 0
catch error
alert error.message
path
getUrlNoQueries: (url) ->
try
if !url
url = window.location.href
if url.indexOf("?") > 0
url = url.split("?")[0]
catch error
alert error.message
url
getUrlPath: (index) ->
url = ""
try
path = window.location.pathname.substring(1)
url = path.split("/")[index] if path.indexOf("/") > 0
catch error
alert error.message
url
getUrlVars: ->
vars = []
try
hash = undefined
hashes = window.location.href.slice(window.location.href.indexOf("?") + 1).split("&")
i = 0
while i < hashes.length
hash = hashes[i].split("=")
vars.push hash[0]
vars[hash[0]] = hash[1]
i++
catch error
alert error.message
vars
removeQueriesFromUrl: ->
try
queries = @getAllQueries()
if queries and queries.length > 0
# Remove all queries from address
path = @getUrlNoQueries()
document.location.href = path
catch error
alert error.message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment