字符串转json以及获取域名的参数

本例将通过location.search来进行字符串拼接成json以及查询域名参数的value

 1 console.log(request('id'));
 2     function request(obj){
 3         var str = 'http://www.baidu.com?staticType=0&type=1&id=123abc';
 4         var str = str.substring(str.indexOf('?')+1);
 5         var arr = str.split('&');
 6         var str1 = '[{';
 7         for(var i=0; i<arr.length;i++)    {
 8             str1 += '"'+arr[i].split('=')[0] +'":"'+arr[i].split('=')[1]+'"'+',';
 9             if(obj == arr[i].split('=')[0]){
10                 return arr[i].split('=')[1] 
11             }
12         }
13         str1 = str1.substring(0,str1.lastIndexOf(','))
14         str1 += '}]';
15         console.log(JSON.parse(str1))
16     }

文章str 假设为获取到的链接地址,?以后的参数可直接通过lcoation.search获取,

然后进行一系列的字符串拼接,第15行显示效果为下图:

至于查询所需的参数,在for循环里面已经做完了,调用的时候直接request(obj)即可返回所需数值,我先调一下id,就是request('id');

打完收工,喜欢的点赞~

原文地址:https://www.cnblogs.com/realdanielwu/p/9041989.html