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

发布于 2024-12-07 20:48:45 字数 585 浏览 0 评论 0原文

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

编辑:我正在对 elements href 而不是页面当前位置执行此操作。

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

这是我到目前为止所得到的,它在第 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);
}

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.

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

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.

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/

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

    alert(url);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

隔岸观火 2024-12-14 20:48:45

不需要在这个上使用 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, '$1' + 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;
}

这是 小提琴

更新:

代码现在处理以下情况: URL 上有一个哈希值。

编辑

错过了一个案例!代码现在检查是否存在查询字符串

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

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, '$1' + 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.

Edit

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

烟雨扶苏 2024-12-14 20:48:45

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

https://github.com/Mikhus/jsurl

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

https://github.com/Mikhus/jsurl

勿忘初心 2024-12-14 20:48:45

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

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

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.

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

很酷不放纵 2024-12-14 20:48:45
<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>
<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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文