javascript将对象转换为url参数

function filter(str) { // 特殊字符转义
  str += ''; // 隐式转换
  str = str.replace(/%/g, '%25');
  str = str.replace(/\+/g, '%2B');
  str = str.replace(/ /g, '%20');
  str = str.replace(/\//g, '%2F');
  str = str.replace(/\?/g, '%3F');
  str = str.replace(/&/g, '%26');
  str = str.replace(/\=/g, '%3D');
  str = str.replace(/#/g, '%23');
  return str;
}

function formateObjToParamStr(paramObj) {
  const sdata = [];
  for (let attr in paramObj) {
    sdata.push(`${attr}=${filter(paramObj[attr])}`);
  }
  return sdata.join('&');
};


const data = {id: '3', name:"chenjianbin", ojb: '3232'}
console.log(formateObjToParamStr(data))
// 返回 id=3&name=chenjianbin&ojb=3232

参考原址 https://www.jianshu.com/p/9c464845ca5b
posted @ 2019-12-26 14:13  我非日葵却也向阳  阅读(4733)  评论(0编辑  收藏  举报