momo3141

parseUrl

Jan 10th, 2023 (edited)
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let url = 'https://www.emag.bg/tavanen-sushilnik-prostor-familia-7-pryta-po-2-0-m-24144780/pd/D82CCJBBM/?ref=fp_growth_atc_3&provider=rec&recid=rec_74_5882c9dbb4c8568aa518710f54be8a643981adb4e51b0506246d48b33c640d10_1673361687&scenario_ID=74';
  2.  
  3. let parseUrl = (str) =>{
  4.     let result = {}
  5.     let protocol = '';
  6.     let host = '';
  7.     let path ='';
  8.     result['query'] = {};
  9.     let a = str.indexOf('://')
  10.     protocol = str.substring(0,a)
  11.     let b = str.indexOf('/', a+3)
  12.     if( b === -1){
  13.         b = str.length;
  14.     }
  15.     host = str.substring(a+3,b)
  16.     let c = str.indexOf('?',b+1)
  17.     if(c === -1){
  18.         c = str.length;
  19.     }
  20.     path = str.substring(b,c)
  21.     result['protocol'] = protocol;
  22.     result['host'] = host;
  23.     result['path'] = path;
  24.     let id = true
  25.     let lable = false
  26.     let tempKey = [];
  27.     let tempValue =[]
  28.     for (let i = c+1 ; i<= str.length - 1; i++){
  29.        
  30.         if(str[i] !== '&' && str[i] !== '='){
  31.             if(id){
  32.                 tempKey.push(str[i])
  33.             } else if (lable) {
  34.                 tempValue.push(str[i])
  35.             }
  36.         } else if (str[i] !== '&' || str[i] !== '='){
  37.             if(id)
  38.              {tempKey.push(' ')}
  39.             if(lable){
  40.                 tempValue.push(' ')
  41.             }
  42.             id = !id;
  43.             lable = !lable
  44.            
  45.         }
  46.        
  47.  
  48.     }
  49.     tempKey = tempKey.join('').split(' ')
  50.     tempKey.pop()
  51.     tempValue = tempValue.join('').split(' ')
  52.     for (let i = 0 ; i <= tempKey.length-1;i++){
  53.         result['query'][tempKey[i]] = tempValue[i]
  54.  
  55.     }
  56.     return result;
  57.  
  58. }
  59. console.log(parseUrl(url));
Advertisement
Add Comment
Please, Sign In to add comment