导航

数组字符串操作

Posted on 2018-05-20 20:39  小飞博客  阅读(278)  评论(0编辑  收藏  举报

替换掉字符串里所有指定的字符串: swtichParse('abc=def=hjk','||')=>'abc||def||hjk'    ,感觉有几点正则的全局g 

1 function swtichParse(str,replaceStrting,targetString){
2     return str.split(replaceStrting).join(targetString)
3 }
4 console.log(swtichParse('abc=def=hjk','=','||'))//abc||def||hjk

替换第一个遇到的目标值

1 function swtichParse(str,replaceStrting,targetString){
2     return str.replace(replaceStrting,targetString)
3 }
4 console.log(swtichParse('abc=def=hjk','=','||'))//abc||def=hjk

url解析

 1 var str='http://www.nowcoder.com?key=1&key=2&key=3&test=4#hehe';
 2 function swtichParse(str,name){
 3     var result={};
 4     str.replace(/\??(\w+)=(\w+)&?/g,function(s,k,v){
 5          if(result[k] !== undefined){
 6             result[k] = [].concat(result[k],v);
 7         }else{
 8             result[k] = v;
 9         }
10     })
11     if(name){
12         return result[name]
13     }else{
14          return result
15     }
16 }
17 console.log(swtichParse(str))//{key: Array(3), test: "4"}
18 console.log(swtichParse(str,'key'))//["1", "2", "3"]
19 console.log(swtichParse(str,'test'))//4

 

 1 var arr = [{a:1}, {b:2}, {c: 3}]
 2 var arr2 = [{c:4},{f:6},{u:9}]
 3 //需求:合并两个JSON数组,如果两个数组里有key相同的,arr2里对应的key值覆盖arr里一样的key的值,没有一样的key,就追加到arr数组里
 4 //[{a:1}, {b:2}, {c: 3}]和[{a:4},{f:6},{u:9}]=>output:[{a:4},{b:2}, {c: 3},{f:6},{u:9}]
 5 //[{a:1}, {b:2}, {c: 3}]和[{f:6},{u:9}]=>output:[{a:1}, {b:2},{c: 3},{f:6},{u:9}]
 6 function mergeArray(arr,arr2){
 7     var arr0=[];
 8     var keyArr=[];
 9     var keyVal=[];
10     var keyArray=[];
11     var keyValue=[];
12     for(let i=0;i<arr2.length;i++){
13         var obj=arr2[i];
14         for(var k in obj){
15             keyArr.push(k)
16             keyVal.push(obj[k])
17         }
18     }
19     for(let j=0;j<arr.length;j++){
20         var obj1=arr[j];
21         for(var key in obj1){
22             keyArray.push(key)
23             keyValue.push(obj1[key])
24         }
25     }
26     for(let i=0;i<keyArray.length;i++ ){
27         if(keyArr.indexOf(keyArray[i])!=-1){
28             var index=keyArr.indexOf(keyArray[i]);
29             keyValue[i]=keyVal[index];
30             keyArr.splice(index,1)
31             keyVal.splice(index,1)
32         }
33     }
34     for(let i=0;i<keyArr.length;i++ ){
35         keyArray.push(keyArr[i])
36         keyValue.push(keyVal[i])
37     }
38     for(let i=0;i<keyArray.length;i++ ){
39         var obj={}
40         obj[keyArray[i]]=keyValue[i];
41         arr0.push(obj)
42     }
43     return arr0
44 }
45 console.log(mergeArray(arr,arr2))