remove url parameters with javascript or jquery

前端 未结 10 2356
臣服心动
臣服心动 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:45

    For example we have:

    example.com/list/search?q=Somethink
    

    And you need use variable url like this by window.location.href:

    example.com/list/edit
    

    From url:

    example.com/list/search?q=Somethink
    example.com/list/
    
    var url = (window.location.href);
        url = url.split('/search')[0];
        url = (url + '/edit');
    

    This is simple solution:-)

    0 讨论(0)
  • 2020-12-25 10:46

    Simple:

    var new_url = old_url.substring(0, old_url.indexOf('?'));
    

    Modified: this will remove all parameters or fragments from url

    var oldURL = [YOUR_URL_TO_REMOVE_PARAMS]
    var index = 0;
    var newURL = oldURL;
    index = oldURL.indexOf('?');
    if(index == -1){
        index = oldURL.indexOf('#');
    }
    if(index != -1){
        newURL = oldURL.substring(0, index);
    }
    
    0 讨论(0)
  • 2020-12-25 10:47

    Hmm... Looking for better way... here it is

    var onlyUrl = window.location.href.replace(window.location.search,'');
    
    0 讨论(0)
  • 2020-12-25 10:48

    This worked for me:

    window.location.replace(window.location.pathname)
    
    0 讨论(0)
  • 2020-12-25 10:51

    Well, I am using this:

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

    or:

        stripUrl(urlToStrip){
            return urlToStrip.split('?')[0].split('&')[0].split('#')[0];
        }
    
    0 讨论(0)
  • 2020-12-25 10:54

    You could use a RegEx to match the value of v and build the URL yourself since you know the URL is 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 讨论(0)
提交回复
热议问题