字符串转对象
javascript开发过程中,经常会遇到字符串转化为对象的操作。最典型的就是url传参时’name=zhangsan&age=10&hobby=pingPong’转化为对象。
for循环转化
function stringToObj(strText,spliceText){
let obj = {}
if(strText =='' || strText == null ){
return {}
}
spliceText = spliceText || ';'
let arr = [];
let j, k , newArr;
arr = strText.split(spliceText)
for(let i = 0; i < arr.length; i++){
newArr = arr[i].split('=')
j = newArr[0]
k = newArr[1]
obj[j] = k
}
return obj
}
console.log(stringToObj('name=zhangsan&age=10&hobby=pingPong',"&"),"dddd")
正则表达式转化
function stringToObj(strText){
var obj = {};
strText.replace(/(\w+)(?:=([^&]*))?/g,function(str, key, value){
obj[key] = value;
});
return obj;
}
console.log(stringToObj('name=zhangsan&age=10&hobby=pingPong'),"666")