params.ts 659 B

1234567891011121314151617181920212223242526
  1. // 字符串转params对象
  2. export const strToParams = (str: string) => {
  3. if (str[0] === '?') {
  4. str = str.substr(1)
  5. }
  6. const result: { [key: string]: string } = {}
  7. const splitRG = /([^=&]+)(?:=([^&]*))?&?/
  8. let rgRet
  9. while ((rgRet = str.match(splitRG))) {
  10. result[rgRet[1]] = rgRet[2] === undefined ? '' : rgRet[2]
  11. str = str.substr(rgRet[0].length)
  12. }
  13. return result
  14. }
  15. // 对象转params
  16. export const paramsToStr = (params: { [key: string]: string | boolean }) =>
  17. '?' +
  18. Object.keys(params)
  19. .filter(key => params[key] !== undefined)
  20. .map(key => `${key}${params[key] == false ? '' : `=${params[key]}`}`)
  21. .join('&')