[javascript] remove url parameters with javascript or jquery

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

but what the api generates is:

youtube.com/watch?v=3sZOD3xKL0Y&feature=youtube_gdata

So what I need to do is be able to select everything after and including the ampersand(&) and remove it from the url.

Any way to do this with javascript and some sort of regular expression?

This question is related to javascript jquery query-string expression

The answer is


Use this function:

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

If you want all the href parts, use this:

_x000D_
_x000D_
var url = document.createElement('a');_x000D_
url.href = 'https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container';_x000D_
_x000D_
console.log(url.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container_x000D_
console.log(url.protocol); // https:_x000D_
console.log(url.host); // developer.mozilla.org_x000D_
console.log(url.hostname); // developer.mozilla.org_x000D_
console.log(url.port); // (blank - https assumes port 443)_x000D_
console.log(url.pathname); // /en-US/search_x000D_
console.log(url.search); // ?q=URL_x000D_
console.log(url.hash); // #search-results-close-container_x000D_
console.log(url.origin); // https://developer.mozilla.org
_x000D_
_x000D_
_x000D_


This worked for me:

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

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));

//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;     
}

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:-)


No splits.. :) The correct/foolproof way is to let the native browser BUILT-IN functions do the heavy lifting using urlParams, the heavy lifting is done for you.

//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!
___________

NOW Putting it all together in your live browser

// 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}`);

Sample working Javascript Fiddle here working sample code to replace query substring and query params


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];
    }

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

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

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];

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to query-string

How can I get (query string) parameters from the URL in Next.js? How to read values from the querystring with ASP.NET Core? What is the difference between URL parameters and query strings? How to get URL parameter using jQuery or plain JavaScript? How to access the GET parameters after "?" in Express? node.js http 'get' request with query string parameters Escaping ampersand in URL In Go's http package, how do I get the query string on a POST request? Append values to query string Node.js: Difference between req.query[] and req.params

Examples related to expression

How do I remove all non-ASCII characters with regex and Notepad++? SSRS Expression for IF, THEN ELSE Regex to get the words after matching string Regular expression to match a word or its prefix SSIS expression: convert date to string Are complex expressions possible in ng-hide / ng-show? Change some value inside the List<T> XPath - Difference between node() and text() javascript - match string against the array of regular expressions Spring cron expression for every after 30 minutes