使用 javascript 在 url 中添加/修改查询字符串/GET 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7640270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:46:05  来源:igfitidea点击:

Adding/Modify query string / GET variables in a url with javascript

javascriptvariablesreplacegetquery-string

提问by MLM

So I am wanting to replace GET variable values in a url and if the variable does not exist, then add it to the url.

因此,我想替换 url 中的 GET 变量值,如果该变量不存在,则将其添加到 url 中。

EDIT: I am doing this to a elements href not the pages current location..

编辑:我这样做是为了元素 href 而不是页面当前位置..

I am not good with javascript but I do know how to use jQuery quite well and the basics of javascript. I do know how to write regex but not how to use the javascript syntax of regex and what functions to use it with.

我不擅长 javascript,但我知道如何很好地使用 jQuery 和 javascript 的基础知识。我知道如何编写正则表达式,但不知道如何使用正则表达式的 javascript 语法以及使用它的函数。

Here is what I have so far and it does have an error on line 3: See it on jsfiddle(or below): http://jsfiddle.net/MadLittleMods/C93mD/

这是我到目前为止所拥有的,它在第 3 行确实有一个错误:在 jsfiddle(或下面)上看到它:http: //jsfiddle.net/MadLittleMods/C93mD/

function addParameter(url, param, value) {
    var pattern = new RegExp(param + '=(.*?);', 'gi');
    return url.replace(pattern, param + '=' + value + ';');

    alert(url);
}

回答by Ryan Kinal

No need to use jQuery on this one. Regular Expressions and string functions are sufficient. See my commented code below:

不需要在这个上使用 jQuery。正则表达式和字符串函数就足够了。请参阅下面的评论代码:

function addParameter(url, param, value) {
    // Using a positive lookahead (?=\=) to find the
    // given parameter, preceded by a ? or &, and followed
    // by a = with a value after than (using a non-greedy selector)
    // and then followed by a & or the end of the string
    var val = new RegExp('(\?|\&)' + param + '=.*?(?=(&|$))'),
        parts = url.toString().split('#'),
        url = parts[0],
        hash = parts[1]
        qstring = /\?.+$/,
        newURL = url;

    // Check if the parameter exists
    if (val.test(url))
    {
        // if it does, replace it, using the captured group
        // to determine & or ? at the beginning
        newURL = url.replace(val, '' + param + '=' + value);
    }
    else if (qstring.test(url))
    {
        // otherwise, if there is a query string at all
        // add the param to the end of it
        newURL = url + '&' + param + '=' + value;
    }
    else
    {
        // if there's no query string, add one
        newURL = url + '?' + param + '=' + value;
    }

    if (hash)
    {
        newURL += '#' + hash;
    }

    return newURL;
}

And here is the Fiddle

这是小提琴

Update:

更新:

The code now handles the case where there is a hash on the URL.

该代码现在处理 URL 上有散列的情况。

Edit

编辑

Missed a case! The code now checks to see if there is a query string at all.

漏了一个案子!现在,该代码检查,看看是否有查询字符串在所有

回答by Joao Leme

I would go with thissmall but complete library to handle urls in js:

我会用这个小而完整的库来处理 js 中的 url:

https://github.com/Mikhus/jsurl

https://github.com/Mikhus/jsurl

回答by Mohamed.Abdo

<script type="text/javascript">
    $(document).ready(function () {
        $('input.letter').click(function () {
            //0- prepare values
            var qsTargeted = 'letter=' + this.value; //"letter=A";
            var windowUrl = '';
            var qskey = qsTargeted.split('=')[0];
            var qsvalue = qsTargeted.split('=')[1];
            //1- get row url
            var originalURL = window.location.href;
            //2- get query string part, and url
            if (originalURL.split('?').length > 1) //qs is exists
            {
                windowUrl = originalURL.split('?')[0];
                var qs = originalURL.split('?')[1];
                //3- get list of query strings
                var qsArray = qs.split('&');
                var flag = false;
                //4- try to find query string key
                for (var i = 0; i < qsArray.length; i++) {
                    if (qsArray[i].split('=').length > 0) {
                        if (qskey == qsArray[i].split('=')[0]) {
                            //exists key
                            qsArray[i] = qskey + '=' + qsvalue;
                            flag = true;
                            break;
                        }
                    }
                }
                if (!flag)//   //5- if exists modify,else add
                {
                    qsArray.push(qsTargeted);
                }
                var finalQs = qsArray.join('&');
                //6- prepare final url
                window.location = windowUrl + '?' + finalQs;
            }
            else {
                //6- prepare final url
                //add query string
                window.location = originalURL + '?' + qsTargeted;
            }
        })
    });
</script>

回答by jtfairbank

See Change URL parameters. It answers your question in a more general manner (changing any url parameter). There are solutions for both jQuery and regular js in the answers section.

请参阅更改 URL 参数。它以更一般的方式回答您的问题(更改任何 url 参数)。答案部分有针对 jQuery 和常规 js 的解决方案。

It also looks like url.replaceshould be location.replacebut I may be wrong (that statement's based on a quick google search for 'url.replace javascript').

它看起来也url.replace应该是,location.replace但我可能错了(该声明基于对“url.replace javascript”的快速谷歌搜索)。