使用JavaScript或jQuery删除URL参数

57

我正在尝试使用YouTube数据API生成视频播放列表。

然而,视频URL需要具有以下格式:

youtube.com/watch?v=3sZOD3xKL0Y

但是API生成的是:

youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata
所以我需要做的是能够选择&之后的所有内容并将其从url中删除。有没有办法使用javascript和某种正则表达式来实现?

请查看此帖子:http://stackoverflow.com/questions/738351/recommendation-for-javascript-url-manipulation-library-api/3215670#3215670 - HasanG
可能是JavaScript对象的查询字符串编码的重复问题。 - Sindre Sorhus
10个回答

106

我错过了什么吗?

为什么不是:

url.split('?')[0] 

运行完美! - vishwarajanand
1
我在想这个简短的解决方案是否存在不适用的情况? - Shining Love Star
@goldylucks 并没有更好的解决方案,这已经是一个完全足够的解决方案了! - Oli C
3
为什么正好过了五年,这不是答案吗? - hellomello
我同意,这比我近十年前的幼稚回答好多了。 - Jacob Relkin
它还会删除任何URI片段,这可能不是您想要的。 - Utsav Chatterjee

29

嗯...在寻找更好的方法...在这里

var onlyUrl = window.location.href.replace(window.location.search,'');

这是我重新加载页面而不带参数的特定情况: window.location.assign(window.location.href.replace(window.location.search,'')); - gtamborero

25

例子: http://jsfiddle.net/SjrqF/

var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';

url = url.slice( 0, url.indexOf('&') );

或者:

示例: http://jsfiddle.net/SjrqF/1/

var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';

url = url.split( '&' )[0];

11

使用这个函数:

var getCleanUrl = function(url) {
  return url.replace(/#.*$/, '').replace(/\?.*$/, '');
};

// get rid of hash and params
console.log(getCleanUrl('https://sidanmor.com/?firstname=idan&lastname=mor'));

如果你想获取所有的href部分,可以使用以下代码:

var url = document.createElement('a');
url.href = 'https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container';

console.log(url.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container
console.log(url.protocol); // https:
console.log(url.host); // developer.mozilla.org
console.log(url.hostname); // developer.mozilla.org
console.log(url.port); // (blank - https assumes port 443)
console.log(url.pathname); // /en-US/search
console.log(url.search); // ?q=URL
console.log(url.hash); // #search-results-close-container
console.log(url.origin); // https://developer.mozilla.org


6
//user113716 code is working but i altered as below. it will work if your URL contain "?" mark or not
//replace URL in browser
if(window.location.href.indexOf("?") > -1) {
    var newUrl = refineUrl();
    window.history.pushState("object or string", "Title", "/"+newUrl );
}

function refineUrl()
{
    //get full url
    var url = window.location.href;
    //get url after/  
    var value = url = url.slice( 0, url.indexOf('?') );
    //get the part after before ?
    value  = value.replace('@System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]','');  
    return value;     
}

5
这个对我有帮助:

最初的回答:

window.location.replace(window.location.pathname)

3

不要拆分参数 :) 正确/可靠的方法是使用浏览器原生内置函数,使用urlParams让浏览器为您完成繁重的工作。

//summary answer - this one line will correctly replace in all current browsers
window.history.replaceState({}, '', `${location.pathname}?${params}`);

// 1 Get your URL 
let url = new URL('https://tykt.org?unicorn=1&printer=2&scanner=3');
console.log("URL: "+ url.toString());

// 2 get your params
let params = new URLSearchParams(url.search);
console.log("querys: " + params.toString());

// 3 Delete the printer param, Query string is now gone
params.delete('printer'); 
console.log("Printer Removed: " + params.toString()); 

// BELOW = Add it back to the URL, DONE!
___________

现在把所有内容整合到您的实时浏览器中

// Above is a breakdown of how to get your params
// 4 then you simply replace those in your current browser!! 
window.history.replaceState({}, '', `${location.pathname}?${params}`);

这里是一个可用的JavaScript演示链接 替换查询子字符串和查询参数的工作样本代码


1

嗯,我正在使用这个:

stripUrl(urlToStrip){
        let stripped = urlToStrip.split('?')[0];
        stripped = stripped.split('&')[0];
        stripped = stripped.split('#')[0];
        return stripped;
    }

或者:

    stripUrl(urlToStrip){
        return urlToStrip.split('?')[0].split('&')[0].split('#')[0];
    }

1
你可以使用正则表达式匹配v的值,并自己构建URL,因为你知道该URL是youtube.com/watch?v=...

http://jsfiddle.net/akURz/

var url = 'http://youtube.com/watch?v=3sZOD3xKL0Y';
alert(url.match(/v\=([a-z0-9]+)/i));

0

例如,我们有:

example.com/list/search?q=Somethink

你需要使用变量url,像这样通过window.location.href

example.com/list/edit

从URL:

example.com/list/search?q=Somethink
example.com/list/

var url = (window.location.href);
    url = url.split('/search')[0];
    url = (url + '/edit');

这是一个简单的解决方案:-)


请提供一个合适的解决方案,这仅适用于/search模式,如果我想使用*值或任何值怎么办? - rohitcoder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接