返回列表

hui.parseLocator/hui.addParam 解析和操作url的query参数

默认分类 2018/06/01 02:24

解析和操作url的query参数

/**
 * @method hui.parseLocator
 * @description 解析url
 * @public
 * @param {String} url URL地址
 * @param {String} args 参数 lower|upper|group
 * @example 
 * hui.parseLocator(window.location.href, 'lower')
 */
var hui = {}
hui.parseLocator = function(url, args) {
  url = url === null || url === undefined ? '' : String(url)
  var query = {},
    list,
    str

  if (url.indexOf('?') !== -1) {
    list = url.split('?')[1].split('#')[0].split('&')
    for (var i = 0, len = list.length; i < len; i++) {
      str = list[i].split('=')
      str.push('')

      var key = str[0]
      if (args && args.indexOf('lower') > -1) key = String(str[0]).toLowerCase()
      else if (args && args.indexOf('upper') > -1) key = String(str[0]).toUpperCase()

      if (args && args.indexOf('group') > -1) {
        if (query[key]) query[key].push(str[1])
        else query[key] = [str[1]]
      } else query[key] = str[1]
    }

    for (var j in query) {
      if (query[j] && query[j].length === 1) {
        query[j] = query[j][0]
      }
    }

  }
  return query
}

/**
 * @method hui.addParam
 * @description 拼接url参数
 * @public
 * @param {String} url URL地址
 * @param {Object} params 待拼接参数
 * @example 
 * hui.addParam(window.location.href, {a:123,b:456})
 * hui.addParam({a:123,b:456})
 */
hui.addParam = function(url, params) {
  params = params || {}
  params = JSON.parse(JSON.stringify(params))

  var sep = url.split('#') // ['http://www.google.com/p/?a=1&b=2?a=5&', '/login?c=123', '!/aaa']
  var a1 = sep.shift() // http://www.google.com/p/?a=1&b=2?a=5&
  var a2 = a1 + '?' // http://www.google.com/p/?a=1&b=2?a=5&??
  var b1 = a2.substring(0, a2.indexOf('?')) // http://www.google.com/p/
  var c1 = a2.substring(a2.indexOf('?') + 1, Math.max(a2.indexOf('?') + 1, a2.length - 1)) // a=1&b=2?a=5&
  var list = c1.split('&')
  var i, row, kk
  for (i = list.length - 1; i > -1; i--) {
    row = list[i]
    kk = row.split('=')[0]
    if (params.hasOwnProperty(kk)) {
      if (params[kk] !== '') {
        list[i] = kk + '=' + window.encodeURIComponent(params[kk])
      } else list.splice(i, 1)
      delete params[kk]
    }
  }
  for (kk in params) {
    if (!params.hasOwnProperty(kk)) continue;
    if (params[kk] === '') continue;
    // 注:如果直接push会导致空字符串占位问题
    if (!list[0]) list[0] = kk + '=' + window.encodeURIComponent(params[kk])
    else list.push(kk + '=' + window.encodeURIComponent(params[kk]))
  }

  var query = list.join('&')
  var hash = sep.join('#')
  var result = b1 + (query === '' ? '' : '?' + query) + (hash === '' ? '' : '#' + hash)

  return result
}

hui.addParam('http://www.google.com/p/?a=1&b=2?a=5&#/login?c=123#!/aaa', {a: 123})