使用JavaScript删除URL的参数 [英] Remove a parameter to the URL with JavaScript

查看:502
本文介绍了使用JavaScript删除URL的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

原始网址:

http://yourewebsite.php?id=10&color_id=1

产生的网址:

http://yourewebsite.php?id=10

我得到了添加Param的函数

I got the function adding Param

function insertParam(key, value){
    key = escape(key); value = escape(value);
    var kvp = document.location.search.substr(1).split('&');
    var i=kvp.length; var x; while(i--) 
    {
        x = kvp[i].split('=');

        if (x[0]==key)
        {
            x[1] = value;
            kvp[i] = x.join('=');
            break;
        }
    }
    if(i<0) {kvp[kvp.length] = [key,value].join('=');}

    //this will reload the page, it's likely better to store this until finished
    document.location.search = kvp.join('&'); 
}

但我需要运行以删除Param

but I need to function to remove Param

推荐答案

试试这个。只需传入要从URL和原始URL值中删除的参数,该函数就会为您删除它。

Try this. Just pass in the param you want to remove from the URL and the original URL value, and the function will strip it out for you.

function removeParam(key, sourceURL) {
    var rtn = sourceURL.split("?")[0],
        param,
        params_arr = [],
        queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : "";
    if (queryString !== "") {
        params_arr = queryString.split("&");
        for (var i = params_arr.length - 1; i >= 0; i -= 1) {
            param = params_arr[i].split("=")[0];
            if (param === key) {
                params_arr.splice(i, 1);
            }
        }
        rtn = rtn + "?" + params_arr.join("&");
    }
    return rtn;
}

要使用它,只需执行以下操作:

To use it, simply do something like this:

var originalURL = "http://yourewebsite.com?id=10&color_id=1";
var alteredURL = removeParam("color_id", originalURL);

var changedURL 将是你的输出欲望。

The var alteredURL will be the output you desire.

希望它有所帮助!

这篇关于使用JavaScript删除URL的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆