在javascript中从网址创建帖子正文

时间:2018-06-18 14:19:20

标签: javascript object url

假设我有一个包含如下参数的网址:

allowedCardTypes=master%2Cvisa&callbackUrl=https%3A%2F%2Fstage.masterpassteststore.com%2Fteststorefront%2F%3Fsdk%3Djava%23%2Fcallback%2Fcheckout%3Freload%3Dtrue&merchantCheckoutId=f5d29dd838bd4e97a280a9e2a00d9f63

我想像这样创建和反对:

{
  allowedCardTypes: master%2Cvisa,
  callbackUrl: https%3A%2F%2Fstage.masterpassteststore.com%2Fteststorefront%2F%3Fsdk%3Djava%23%2Fcallback%2Fcheckout%3Freload%3Dtrue

}

有什么想法吗? js是否具有此功能?

2 个答案:

答案 0 :(得分:2)

是。 https://developer.mozilla.org/en-US/docs/Web/API/URL

此解决方案实际上会为您创建更好的字符串(引号和非转义)

let parms = {"allowedCardTypes":"","callbackUrl":""}
const searchParams = "allowedCardTypes=master%2Cvisa&callbackUrl=https%3A%2F%2Fstage.masterpassteststore.com%2Fteststorefront%2F%3Fsdk%3Djava%23%2Fcallback%2Fcheckout%3Freload%3Dtrue&merchantCheckoutId=f5d29dd838bd4e97a280a9e2a00d9f63"
const url = new URL("http://test.com?"+searchParams);
for (let parm in parms) {
  parms[parm] = url.searchParams.get(parm);
}
console.log(parms);

答案 1 :(得分:0)

由于您的url是一个字符串,您可以将其设置为变量,对其执行一些基本的字符串操作,然后将其保存为对象中的键值对:

var url = "allowedCardTypes=master%2Cvisa&callbackUrl=https%3A%2F%2Fstage.masterpassteststore.com%2Fteststorefront%2F%3Fsdk%3Djava%23%2Fcallback%2Fcheckout%3Freload%3Dtrue&merchantCheckoutId=f5d29dd838bd4e97a280a9e2a00d9f63"

var array = url.split("&callbackUrl=")
//console.log('array is: ', array)

var allowedCarTypesValue = array[0].split("allowedCardTypes=")
//console.log('allowedCarTypesValue: ', allowedCarTypesValue)

var obj = {
  allowedCardTypes: allowedCarTypesValue[1],
  callbackUrl: array[1]
};

console.log('obj is: ', obj)