【问题标题】:Search and remove a parameter with optional character from URL从 URL 中搜索并删除带有可选字符的参数
【发布时间】:2017-11-14 11:59:32
【问题描述】:

我希望通过点击事件从 URL 中删除参数。问题是参数前面可以有&,也可以没有。所以表单是search=MYSEARCHTERM&search=MYSEARCHTERM

我有以下似乎适用于一个或另一个但不能同时适用的以下内容。我在想我可以有一个 if / else 语句,其中一个包含这样的东西。 (请原谅蹩脚的正则表达式,但我以前从未写过)

var searchKeywordRegx = new RegExp(/(?:&)/ + 'search=' + searchKeyword);

$('.searchKeyword').click(function() {
    $(this).remove();
    var searchKeywordRegx = new RegExp('search=' + searchKeyword);
    console.log(searchKeywordRegx);
    document.location.href = String( document.location.href ).replace(searchKeywordRegx , "" );
});

我离基地还远吗?

【问题讨论】:

    标签: javascript jquery regex url


    【解决方案1】:

    使用? 在正则表达式中设置可选内容:

    var searchKeywordRegx = new RegExp('&?search=' + searchKeyword);
    

    【讨论】:

    • 啊!很简单。谢谢
    【解决方案2】:

    似乎你可以在没有正则表达式的情况下做到这一点。如果您只是删除文档位置的“搜索”部分:

    document.location.search = document.location.search
        .replace('search=' + encodeURI(searchKeyword), '');
    

    【讨论】:

    • 我听说过 encodeURI 但我不熟悉。我得去看看。谢谢。
    • @LMG,我正在使用encodeURI,因为它将确保值具有正确的编码字符串。例如,如果字符串是search=testing this(带有空格),那么URL 中的内容就是search=testing%20this。所以encodeURI 确保您传递给它的值将与它在 URL 中的外观相匹配。
    • 感谢您的澄清。
    猜你喜欢
    • 2015-12-28
    • 2022-01-10
    • 2023-04-08
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2013-06-16
    • 2015-11-05
    • 1970-01-01
    相关资源
    最近更新 更多