【问题标题】:Javascript how to remove parameter from URL sting by value?Javascript如何按值从URL字符串中删除参数?
【发布时间】:2018-08-23 10:42:28
【问题描述】:

如何从 URL 字符串中删除带有value = 3 的参数?

示例 URL 字符串:

https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3 

【问题讨论】:

    标签: javascript regex url url-rewriting


    【解决方案1】:

    如果您的目标浏览器支持URLURLSearchParams,您可以遍历URL 的searchParams 对象,检查每个参数的值,并根据需要检查delete()。最后使用URL的href属性得到最终的url。

    var url = new URL(`https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3`)
    
    //need a clone of the searchParams
    //otherwise looping while iterating over
    //it will cause problems
    var params = new URLSearchParams(url.searchParams.toString());
    for(let param of params){
       if(param[1]==3){
         url.searchParams.delete(param[0]);
       }
    }
    console.log(url.href)

    【讨论】:

    • 谢谢!我认为它比正则表达式更好。
    • @mr.boris 查看更新的示例,对其进行迭代并同时删除将导致它跳过条目,因此您必须先进行克隆并循环克隆以防止此问题(它类似于迭代arrays and deleting)
    【解决方案2】:

    有一种方法可以使用单个正则表达式来做到这一点,使用一些魔法,但我相信这需要使用lookbehinds,大多数 JavaScript 正则表达式引擎大多还不支持。作为替代方案,我们可以尝试拆分查询字符串,然后检查每个组件以查看值是否为3。如果是这样,那么我们删除该查询参数。

    var url = "https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3";
    var parts = url.split(/\?/);
    var params = parts[1].replace(/^.*\?/, "").split(/&/);
    var param_out = "";
    params.forEach(function(x){
        if (!/.*=3$/.test(x))
            param_out += x;
    });
    
    url = parts[0] + (param_out !== "" ? "?" + param_out : "");
    console.log(url);

    【讨论】:

    • 谢谢。我认为这是浏览器最支持的方法!
    【解决方案3】:

    您可以使用正则表达式replace。拆分查询字符串,然后拆分.replace&s(或最初的^)直到=3s:

    const str = 'https://www.example.com/test/index.html?param1=4&param2=3&param3=2&param4=1&param5=3';
    const [base, qs] = str.split('?');
    const replacedQs = qs.replace(/(^|&)[^=]+=3\b/g, '');
    const output = base + (replacedQs ? '?' + replacedQs : '');
    console.log(output);

    【讨论】:

    • 您的输出仍然显示param5=3。我虽然 OP 想删除它。
    • @CertainPerformance 其实你的回答有点儿incorrect
    • @mr.boris 我的错误,我想我现在已经修复了
    • 您的解决方案仍然存在问题,因为如果 all 查询参数的值为 3,它仍然会在 URL 的末尾留下一个悬空的 ?See here.
    猜你喜欢
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-10
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    相关资源
    最近更新 更多