Get the Query String with Coffeescript as Associative Array

Below there is the Coffescript version of the function from this previous post, that returns an associative array containing field-value pairs from the query string:

getQueryString = ->
  vars = []

  # Get the start index of the query string
  qsi = window.location.href.indexOf("?")
  return vars if qsi is -1

  # Get the query string
  qs = window.location.href.slice(qsi + 1)

  # Check if there is a subsection reference
  sri = qs.indexOf("#")
  qs = qs.slice(0, sri) if sri >= 0

  # Build the associative array
  hashes = qs.split("&")
  for hash in hashes
    sep = hash.indexOf("=")
    continue if sep <= 0
    key = decodeURIComponent(hash.slice(0, sep))
    val = decodeURIComponent(hash.slice(sep + 1))
    vars[key] = val

  vars

Example usage:

# Get the query string
queryString = getQueryString()

# Print all field-value pairs
for k of queryString
  console.log (k + " ==> " + queryString[k]);

# Check if the field "a" exists
console.log queryString["a"] if queryString["a"] isnt `undefined`

# Get the value for the field "b"
b = queryString["b"]

# Assign a value for the field "c"
queryString["c"] = "10"
  • jonmadison

    vars = {}

Categories

Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow

Comments

Developed and designed by Netgloo
© 2019 Netgloo