remove url parameters with javascript or jquery

前端 未结 10 2357
臣服心动
臣服心动 2020-12-25 10:15

I am trying to use the youtube data api to generate a video playlist.

However, the video urls require a format of:

youtube.com/watch?v=3sZOD3xKL0Y
<         


        
相关标签:
10条回答
  • 2020-12-25 10:58

    Use this function:

    var getCleanUrl = function(url) {
      return url.replace(/#.*$/, '').replace(/\?.*$/, '');
    };
    
    // get rid of hash and params
    console.log(getCleanUrl('https://sidanmor.com/?firstname=idan&lastname=mor'));

    If you want all the href parts, use this:

    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

    0 讨论(0)
  • 2020-12-25 11:05
    //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;     
    }
    
    0 讨论(0)
  • 2020-12-25 11:07

    What am I missing?

    Why not:

    url.split('?')[0] 
    
    0 讨论(0)
  • 2020-12-25 11:08

    Example: http://jsfiddle.net/SjrqF/

    var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';
    
    url = url.slice( 0, url.indexOf('&') );
    

    or:

    Example: http://jsfiddle.net/SjrqF/1/

    var url = 'youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata';
    
    url = url.split( '&' )[0];
    
    0 讨论(0)
提交回复
热议问题