代码之家  ›  专栏  ›  技术社区  ›  lrr59

拆分字符串中存在的查询参数然后进行编码的最佳方法

  •  0
  • lrr59  · 技术社区  · 4 周前

    我有几个字符串可以是这种格式:

    const s1 = "https://test1.com/testPage";
    const s2 = "https://test2.com/testPage?specificParam=1"
    const s3 = "https://test3.com/someOtherPage?specificParam=2&restParam=3";
    
    

    因此,当我在函数中读取它时,我必须检查字符串是否包含查询参数,如果是,则我必须使用它进行编码 window.btoa() 到所有查询参数。如果不直接重定向。有人能帮忙做这件事吗?

    function test(path){
       const href = window.location.origin + path;
       if(href.includes('?')){
          // split all the query params and then attach `btoa` to it and then openthe url 
           with encoded params
       }
       window.open(href, '_blank', 'no-referer');
    } 
    
    1 回复  |  直到 4 周前
        1
  •  2
  •   Unmitigated    4 周前

    您可以使用 URL 构造函数。

    const url = new URL("https://test3.com/someOtherPage?specificParam=2&restParam=3");
    if (url.search) {
        // use url.search or url.searchParams
        // base64 encode each query param value
        url.search = new URLSearchParams([...url.searchParams].map(([k, v]) => [k, btoa(v)]));
    }