web123456

js splicing URL string

In actual development, you often encounter http requests (especially get requests) or jump to the page and need to splice URL request strings, and the regular thinking is to use "+" to splice strings:

var baseUrl = ''
var a = 1, b = 'request', c = true
var finalUrl = baseUrl + '?a=' + a + '&b=' + b + '&c=' + c

This method looks ugly and clumsy and the least elegant.

A more advanced point is to use es6 "" for splicing:

const finalUrl = `${baseUrl}?a=${a}&b=${b}&c=${c}`

I felt relieved, the code was small and it was relatively simple.

There is also a recommended way of writing, which is also very suitable for actual project development, that is, to convert the object form into a URL request string code extracted into a tool function, and import it when needed:

/**
  * The splicing object is a request string
  *@param{Object} obj - Object to be spliced
  *@returns{string} - a spliced ​​request string
  */export function encodeSearchParams(obj) {
  const params = []

  (obj).forEach((key) => {
    let value = obj[key]
    //If the value isundefinedWe put it emptyif (typeof value === 'undefined') {
      value = ''
    }
    //For text that needs to be encoded (such as Chinese) we need to encode
     ([key, encodeURIComponent(value)].join('='))
  })

  return params.join('&')
}

Then use the posture:

const obj = {
    a: 1,
    b: 'request',
    c: true,
}

const finalUrl = `${baseUrl}?${encodeSearchParams(obj)}`

No more repeating the annoying odd and double quotes and ${} placeholders

Convenient and elegant - so cool that I can't breathe~