JavaScript converts an object into a URL parameter

Ren Lei ABC 2022-02-13 06:47:31 阅读数:61

javascript converts object url parameter
function filter(str) { // Special character escape
str += ''; // Implicit conversion
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))
// return id=3&name=chenjianbin&ojb=3232
copyright:author[Ren Lei ABC],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130647298476.html