Posted in Javascript onSeptember 25, 2016
朋友问的一个面试题:有个url,要求获取url 的参数,返回值为json格式。
简单的写了下,发笔记备份。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>simple a example for url to json</title> <script> var url = 'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd=慕课&rsv_pq=e379bd8200001a8c&rsv_t=ea8cxrgm03IFb44zHA261P6KziPRXAekcjwsRJtUSKLUmKweFsZFXE%2BUSrU&rqlang=cn&rsv_enter=0&rs'; function url2json(url){ var index = -1, str = '', arr = [], length = 0, res = {}; if(url.indexOf('?')!=-1){ index = url.indexOf('?'); str = url.substring(index+1); arr = str.split('&'); length = arr.length; for(var i=0; i<length-1; i++){ res[arr[i].split('=')[0]] = arr[i].split('=')[1]; } }else{ res = {}; } return res; }; var result = url2json(url); //获取json的键值对条数(模拟长度) var length = 0; for(var i in result){ length++; } //在页面输出 var tL = 0; document.write('{<br>'); for(var name in result){ tL++; if(tL == length){ document.write('  '+name+':'+result[name]+'<br>'); }else{ document.write('  '+name+':'+result[name]+',<br>'); } } document.write('}'); </script> </head> <body>
JavaScript实现url参数转成json形式
- Author -
differ_wy声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@