How to split url to get url path in JavaScript - javascript

I have constructed a url path that are pointing to different hostname www.mysite.com, so for example:
var myMainSite = 'www.mymainsite.com' + '/somepath';
so this is equivalent to www.mymainsite.com/path/path/needthispath/somepath.
How I'm doing it now is like the code below and this gives me a bunch of indexes of the url in the console.log.
var splitUrl = myMainSite.split('/');
console.log looks like:
0: http://
1: www.
2: mysite.com
3: path
4: path
5: needthispath
6: somepath
and I concat them like splitUrl[5]+'/'+splitUrl[6] and it doesn't look pretty at all.
So my question is how to split/remove url location http://www.mymainsite.com/ to get the url path needthispath/somepath in js? Is there a quicker and cleaner way of doing this?

First solution (URL object)
The URL object can be used for parsing, constructing, normalizing, encoding URLs, and so on.
var url = 'http://www.mymainsite.com/somepath/path2/path3/path4';
var pathname = new URL(url).pathname;
console.log(pathname);
The URL interface represents an object providing static methods used
for creating object URLs.
See the documentation for URL interface on Mozilla MDN
The Browser support is pretty good in 2017 (~ 90% but not IE11 nor below)
Second solution (a kind of a hack)
var urlHack = document.createElement('a');
urlHack.href = 'http://www.mymainsite.com/somepath/path2/path3/path4';
console.log(urlHack.pathname);
// you can even call this object with these properties:
// protocol, host, hostname, port, pathname, hash, search, origin

Why don't you use the split function and work from there.
The split function will break your URL out fully and from there you just need to look for the second last and last items.
Here is an example:
var initial_url = 'http://www.mymainsite.com/path/path/needthispath/somepath';
var url = initial_url .split( '/' );
var updated_url= document.location.hostname + '/' + url[ url.length - 2 ] + '/' + url[ url.length - 1 ];

You can use the URL API, though support is variable.
Alternatively, you could use URI.js.
Both allow you to get different parts of an URL, as well as build new URLs from parts.

function url($url) {
var url = $url.split( '//' );
if (url[0] === "http:" || url[0] === "https:") {
var protocol = url[0] + "//";
var host = url[1].split( '/' )[0];
url = protocol + host;
var path = $url.split(url)[1];
return {
protocol: protocol,
host: host,
path: path
};
}
}
var $url = url("http://www.mymainsite.com/path/path/needthispath/somepath");
console.log($url.protocol); // http://
console.log($url.host); // www.mymainsite.com
console.log($url.path); // /path/path/needthispath/somepath

Related

Remove URL parameters on button click JQuery/JavaScript [duplicate]

I am trying to remove everything after the "?" in the browser url on document ready.
Here is what I am trying:
jQuery(document).ready(function($) {
var url = window.location.href;
url = url.split('?')[0];
});
I can do this and see it the below works:
jQuery(document).ready(function($) {
var url = window.location.href;
alert(url.split('?')[0]);
});
TL;DR
1- To modify current URL and add / inject it (the new modified URL) as a new URL entry to history list, use pushState:
window.history.pushState({}, document.title, "/" + "my-new-url.html");
2- To replace current URL without adding it to history entries, use replaceState:
window.history.replaceState({}, document.title, "/" + "my-new-url.html");
3- Depending on your business logic, pushState will be useful in cases such as:
you want to support the browser's back button
you want to create a new URL, add/insert/push the new URL to history entries, and make it current URL
allowing users to bookmark the page with the same parameters (to show the same contents)
to programmatically access the data through the stateObj then parse from the anchor
As I understood from your comment, you want to clean your URL without redirecting again.
Note that you cannot change the whole URL. You can just change what comes after the domain's name. This means that you cannot change www.example.com/ but you can change what comes after .com/
www.example.com/old-page-name => can become => www.example.com/myNewPaage20180322.php
Background
We can use:
1- The pushState() method if you want to add a new modified URL to history entries.
2- The replaceState() method if you want to update/replace current history entry.
.replaceState() operates exactly like .pushState() except that .replaceState() modifies the current history entry instead of creating a new one. Note that this doesn't prevent the creation of a new entry in the global browser history.
.replaceState() is particularly useful when you want to update the
state object or URL of the current history entry in response to some
user action.
Code
To do that I will use The pushState() method for this example which works similarly to the following format:
var myNewURL = "my-new-URL.php";//the new URL
window.history.pushState("object or string", "Title", "/" + myNewURL );
Feel free to replace pushState with replaceState based on your requirements.
You can substitute the paramter "object or string" with {} and "Title" with document.title so the final statment will become:
window.history.pushState({}, document.title, "/" + myNewURL );
Results
The previous two lines of code will make a URL such as:
https://domain.tld/some/randome/url/which/will/be/deleted/
To become:
https://domain.tld/my-new-url.php
Action
Now let's try a different approach. Say you need to keep the file's name. The file name comes after the last / and before the query string ?.
http://www.someDomain.com/really/long/address/keepThisLastOne.php?name=john
Will be:
http://www.someDomain.com/keepThisLastOne.php
Something like this will get it working:
//fetch new URL
//refineURL() gives you the freedom to alter the URL string based on your needs.
var myNewURL = refineURL();
//here you pass the new URL extension you want to appear after the domains '/'. Note that the previous identifiers or "query string" will be replaced.
window.history.pushState("object or string", "Title", "/" + myNewURL );
//Helper function to extract the URL between the last '/' and before '?'
//If URL is www.example.com/one/two/file.php?user=55 this function will return 'file.php'
//pseudo code: edit to match your URL settings
function refineURL()
{
//get full URL
var currURL= window.location.href; //get current address
//Get the URL between what's after '/' and befor '?'
//1- get URL after'/'
var afterDomain= currURL.substring(currURL.lastIndexOf('/') + 1);
//2- get the part before '?'
var beforeQueryString= afterDomain.split("?")[0];
return beforeQueryString;
}
UPDATE:
For one liner fans, try this out in your console/firebug and this page URL will change:
window.history.pushState("object or string", "Title", "/"+window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split("?")[0]);
This page URL will change from:
http://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page/22753103#22753103
To
http://stackoverflow.com/22753103#22753103
Note: as Samuel Liew indicated in the comments below, this feature has been introduced only for HTML5.
An alternative approach would be to actually redirect your page (but you will lose the query string `?', is it still needed or the data has been processed?).
window.location.href = window.location.href.split("?")[0]; //"http://www.newurl.com";
Note 2:
Firefox seems to ignore window.history.pushState({}, document.title, ''); when the last argument is an empty string. Adding a slash ('/') worked as expected and removed the whole query part of the url string.
Chrome seems to be fine with an empty string.
These are all misleading, you never want to add to the browser history unless you want to go to a different page in a single page app. If you want to remove the parameters without a change in the page, you must use:
window.history.replaceState(null, null, window.location.pathname);
I belive the best and simplest method for this is:
var newURL = location.href.split("?")[0];
window.history.pushState('object', document.title, newURL);
a simple way to do this, works on any page, requires HTML 5
// get the string following the ?
var query = window.location.search.substring(1)
// is there anything there ?
if(query.length) {
// are the new history methods available ?
if(window.history != undefined && window.history.pushState != undefined) {
// if pushstate exists, add a new state to the history, this changes the url without reloading the page
window.history.pushState({}, document.title, window.location.pathname);
}
}
I wanted to remove only one param success. Here's how you can do this:
let params = new URLSearchParams(location.search)
params.delete('success')
history.replaceState(null, '', '?' + params + location.hash)
This also retains #hash.
URLSearchParams won't work on IE, but being worked on for Edge. You can use a polyfill or a could use a naïve helper function for IE-support:
function take_param(key) {
var params = new Map(location.search.slice(1).split('&')
.map(function(p) { return p.split(/=(.*)/) }))
var value = params.get(key)
params.delete(key)
var search = Array.from(params.entries()).map(
function(v){ return v[0]+'='+v[1] }).join('&')
return {search: search ? '?' + search : '', value: value}
}
This can be used like:
history.replaceState(
null, '', take_param('success').search + location.hash)
Better solution :
window.history.pushState(null, null, window.location.pathname);
if I have a special tag at the end of my URL like: http://domain.com/?tag=12345
Here is the below code to remove that tag whenever it presents in the URL:
<script>
// Remove URL Tag Parameter from Address Bar
if (window.parent.location.href.match(/tag=/)){
if (typeof (history.pushState) != "undefined") {
var obj = { Title: document.title, Url: window.parent.location.pathname };
history.pushState(obj, obj.Title, obj.Url);
} else {
window.parent.location = window.parent.location.pathname;
}
}
</script>
This gives the idea to remove one or more (or all) parameters from URL
With window.location.pathname you basically get everything before '?' in the url.
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
None of these solutions really worked for me, here is a IE11-compatible function that can also remove multiple parameters:
/**
* Removes URL parameters
* #param removeParams - param array
*/
function removeURLParameters(removeParams) {
const deleteRegex = new RegExp(removeParams.join('=|') + '=')
const params = location.search.slice(1).split('&')
let search = []
for (let i = 0; i < params.length; i++) if (deleteRegex.test(params[i]) === false) search.push(params[i])
window.history.replaceState({}, document.title, location.pathname + (search.length ? '?' + search.join('&') : '') + location.hash)
}
removeURLParameters(['param1', 'param2'])
var currURL = window.location.href;
var url = (currURL.split(window.location.host)[1]).split("?")[0];
window.history.pushState({}, document.title, url);
This will be a cleaner way to clear only query string.
//Joraid 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;
}
To clear out all the parameters, without doing a page refresh, AND if you are using HTML5, then you can do this:
history.pushState({}, '', 'index.html' ); //replace 'index.html' with whatever your page name is
This will add an entry in the browser history. You could also consider replaceState if you don't wan't to add a new entry and just want to replace the old entry.
a single line solution :
history.replaceState && history.replaceState(
null, '', location.pathname + location.search.replace(/[\?&]my_parameter=[^&]+/, '').replace(/^&/, '?')
);
credits : https://gist.github.com/simonw/9445b8c24ddfcbb856ec
Here is an ES6 one liner which preserves the location hash and does not pollute browser history by using replaceState:
(l=>{window.history.replaceState({},'',l.pathname+l.hash)})(location)
Running this js for me cleared any params on the current url without refreshing the page.
window.history.replaceState({}, document.title, location.protocol + '//' + location.host + location.pathname);
Here is how can specific query param be removed (even if repeated), without removing other query params:
const newUrl = new URL(location.href);
newUrl.searchParams.delete('deal');
window.history.replaceState({}, document.title, newUrl.href);
In Javascript:
window.location.href = window.location.href.split("?")[0]

What is the best way to determine if a URL belongs to the current domain in JavaScript?

I have a URL. It might be relative (e.g. not start with https://, etc.), or it might not be (starts with https://, etc.).
How can I determine if this URL refers to the same domain as window.location?
(I'm creating a XMLHttpRequest and adding a cookie to it. Can only add the cookie if the URL I'm requesting is the same as the one I'm at. It's a secret cookie.)
The simplest way is actually to leverage the DOM: when you insert a URL into an <a> tag, the browser will actually resolve the URL immediately—i.e. when you retrieve the element's href attribute using JS, it will return an absolute path.
Then, you can simply check if the resolved path contains window.location.origin:
function doesUrlBelongsToCurrentDomain(url) {
const link = document.createElement('a');
link.href = url;
return link.href.includes(window.location.origin);
}
console.log(doesUrlBelongsToCurrentDomain('https://google.com')); // false
console.log(doesUrlBelongsToCurrentDomain('./relative-link')); // true
console.log(doesUrlBelongsToCurrentDomain('/relative-link')); // true
For a ES5-compliant version, swap String.prototype.includes with String.prototype.indexOf:
return link.href.indexOf(window.location.origin) !== -1;
Also, if your browser does not support window.location.origin, you will need to construct it manually:
var origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
...therefore, the IE11-compatible version (if IE11 support is absolutely needed), will be as follow:
function doesUrlBelongsToCurrentDomain(url) {
var link = document.createElement('a');
link.href = url;
var origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? ':' + window.location.port : '');
return link.href.indexOf(origin) !== -1;
}
You can create an URL object from the url to test, and compare it to the current location origin:
const sameOrigin = new URL('URL_TO_TEST').origin === window.location.origin;

Remove URL parameters without refreshing page

I am trying to remove everything after the "?" in the browser url on document ready.
Here is what I am trying:
jQuery(document).ready(function($) {
var url = window.location.href;
url = url.split('?')[0];
});
I can do this and see it the below works:
jQuery(document).ready(function($) {
var url = window.location.href;
alert(url.split('?')[0]);
});
TL;DR
1- To modify current URL and add / inject it (the new modified URL) as a new URL entry to history list, use pushState:
window.history.pushState({}, document.title, "/" + "my-new-url.html");
2- To replace current URL without adding it to history entries, use replaceState:
window.history.replaceState({}, document.title, "/" + "my-new-url.html");
3- Depending on your business logic, pushState will be useful in cases such as:
you want to support the browser's back button
you want to create a new URL, add/insert/push the new URL to history entries, and make it current URL
allowing users to bookmark the page with the same parameters (to show the same contents)
to programmatically access the data through the stateObj then parse from the anchor
As I understood from your comment, you want to clean your URL without redirecting again.
Note that you cannot change the whole URL. You can just change what comes after the domain's name. This means that you cannot change www.example.com/ but you can change what comes after .com/
www.example.com/old-page-name => can become => www.example.com/myNewPaage20180322.php
Background
We can use:
1- The pushState() method if you want to add a new modified URL to history entries.
2- The replaceState() method if you want to update/replace current history entry.
.replaceState() operates exactly like .pushState() except that .replaceState() modifies the current history entry instead of creating a new one. Note that this doesn't prevent the creation of a new entry in the global browser history.
.replaceState() is particularly useful when you want to update the
state object or URL of the current history entry in response to some
user action.
Code
To do that I will use The pushState() method for this example which works similarly to the following format:
var myNewURL = "my-new-URL.php";//the new URL
window.history.pushState("object or string", "Title", "/" + myNewURL );
Feel free to replace pushState with replaceState based on your requirements.
You can substitute the paramter "object or string" with {} and "Title" with document.title so the final statment will become:
window.history.pushState({}, document.title, "/" + myNewURL );
Results
The previous two lines of code will make a URL such as:
https://domain.tld/some/randome/url/which/will/be/deleted/
To become:
https://domain.tld/my-new-url.php
Action
Now let's try a different approach. Say you need to keep the file's name. The file name comes after the last / and before the query string ?.
http://www.someDomain.com/really/long/address/keepThisLastOne.php?name=john
Will be:
http://www.someDomain.com/keepThisLastOne.php
Something like this will get it working:
//fetch new URL
//refineURL() gives you the freedom to alter the URL string based on your needs.
var myNewURL = refineURL();
//here you pass the new URL extension you want to appear after the domains '/'. Note that the previous identifiers or "query string" will be replaced.
window.history.pushState("object or string", "Title", "/" + myNewURL );
//Helper function to extract the URL between the last '/' and before '?'
//If URL is www.example.com/one/two/file.php?user=55 this function will return 'file.php'
//pseudo code: edit to match your URL settings
function refineURL()
{
//get full URL
var currURL= window.location.href; //get current address
//Get the URL between what's after '/' and befor '?'
//1- get URL after'/'
var afterDomain= currURL.substring(currURL.lastIndexOf('/') + 1);
//2- get the part before '?'
var beforeQueryString= afterDomain.split("?")[0];
return beforeQueryString;
}
UPDATE:
For one liner fans, try this out in your console/firebug and this page URL will change:
window.history.pushState("object or string", "Title", "/"+window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split("?")[0]);
This page URL will change from:
http://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page/22753103#22753103
To
http://stackoverflow.com/22753103#22753103
Note: as Samuel Liew indicated in the comments below, this feature has been introduced only for HTML5.
An alternative approach would be to actually redirect your page (but you will lose the query string `?', is it still needed or the data has been processed?).
window.location.href = window.location.href.split("?")[0]; //"http://www.newurl.com";
Note 2:
Firefox seems to ignore window.history.pushState({}, document.title, ''); when the last argument is an empty string. Adding a slash ('/') worked as expected and removed the whole query part of the url string.
Chrome seems to be fine with an empty string.
These are all misleading, you never want to add to the browser history unless you want to go to a different page in a single page app. If you want to remove the parameters without a change in the page, you must use:
window.history.replaceState(null, null, window.location.pathname);
I belive the best and simplest method for this is:
var newURL = location.href.split("?")[0];
window.history.pushState('object', document.title, newURL);
a simple way to do this, works on any page, requires HTML 5
// get the string following the ?
var query = window.location.search.substring(1)
// is there anything there ?
if(query.length) {
// are the new history methods available ?
if(window.history != undefined && window.history.pushState != undefined) {
// if pushstate exists, add a new state to the history, this changes the url without reloading the page
window.history.pushState({}, document.title, window.location.pathname);
}
}
I wanted to remove only one param success. Here's how you can do this:
let params = new URLSearchParams(location.search)
params.delete('success')
history.replaceState(null, '', '?' + params + location.hash)
This also retains #hash.
URLSearchParams won't work on IE, but being worked on for Edge. You can use a polyfill or a could use a naïve helper function for IE-support:
function take_param(key) {
var params = new Map(location.search.slice(1).split('&')
.map(function(p) { return p.split(/=(.*)/) }))
var value = params.get(key)
params.delete(key)
var search = Array.from(params.entries()).map(
function(v){ return v[0]+'='+v[1] }).join('&')
return {search: search ? '?' + search : '', value: value}
}
This can be used like:
history.replaceState(
null, '', take_param('success').search + location.hash)
Better solution :
window.history.pushState(null, null, window.location.pathname);
if I have a special tag at the end of my URL like: http://domain.com/?tag=12345
Here is the below code to remove that tag whenever it presents in the URL:
<script>
// Remove URL Tag Parameter from Address Bar
if (window.parent.location.href.match(/tag=/)){
if (typeof (history.pushState) != "undefined") {
var obj = { Title: document.title, Url: window.parent.location.pathname };
history.pushState(obj, obj.Title, obj.Url);
} else {
window.parent.location = window.parent.location.pathname;
}
}
</script>
This gives the idea to remove one or more (or all) parameters from URL
With window.location.pathname you basically get everything before '?' in the url.
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
None of these solutions really worked for me, here is a IE11-compatible function that can also remove multiple parameters:
/**
* Removes URL parameters
* #param removeParams - param array
*/
function removeURLParameters(removeParams) {
const deleteRegex = new RegExp(removeParams.join('=|') + '=')
const params = location.search.slice(1).split('&')
let search = []
for (let i = 0; i < params.length; i++) if (deleteRegex.test(params[i]) === false) search.push(params[i])
window.history.replaceState({}, document.title, location.pathname + (search.length ? '?' + search.join('&') : '') + location.hash)
}
removeURLParameters(['param1', 'param2'])
var currURL = window.location.href;
var url = (currURL.split(window.location.host)[1]).split("?")[0];
window.history.pushState({}, document.title, url);
This will be a cleaner way to clear only query string.
//Joraid 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;
}
To clear out all the parameters, without doing a page refresh, AND if you are using HTML5, then you can do this:
history.pushState({}, '', 'index.html' ); //replace 'index.html' with whatever your page name is
This will add an entry in the browser history. You could also consider replaceState if you don't wan't to add a new entry and just want to replace the old entry.
a single line solution :
history.replaceState && history.replaceState(
null, '', location.pathname + location.search.replace(/[\?&]my_parameter=[^&]+/, '').replace(/^&/, '?')
);
credits : https://gist.github.com/simonw/9445b8c24ddfcbb856ec
Here is an ES6 one liner which preserves the location hash and does not pollute browser history by using replaceState:
(l=>{window.history.replaceState({},'',l.pathname+l.hash)})(location)
Running this js for me cleared any params on the current url without refreshing the page.
window.history.replaceState({}, document.title, location.protocol + '//' + location.host + location.pathname);
Here is how can specific query param be removed (even if repeated), without removing other query params:
const newUrl = new URL(location.href);
newUrl.searchParams.delete('deal');
window.history.replaceState({}, document.title, newUrl.href);
In Javascript:
window.location.href = window.location.href.split("?")[0]

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?
What am I missing?
Why not:
url.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];
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
//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;
}
This worked for me:
window.location.replace(window.location.pathname)
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
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));
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];
}
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:-)

How to extract the hostname portion of a URL in JavaScript

Is there a really easy way to start from a full URL:
document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah"
And extract just the host part:
aaa.bbb.ccc.com
There's gotta be a JavaScript function that does this reliably, but I can't find it.
Suppose that you have a page with this address: http://sub.domain.com/virtualPath/page.htm.
Use the following in page code to achieve those results:
Property
Result
window.location.host
sub.domain.com:8080 or sub.domain.com:80
window.location.hostname
sub.domain.com
window.location.protocol
http:
window.location.port
8080 or 80
window.location.pathname
/virtualPath
window.location.origin
http://sub.domain.com (Might include :port too*****)
Update: about the .origin
***** As the ref states, browser compatibility for window.location.origin is not clear. I've checked it in chrome and it returned http://sub.domain.com:port if the port is anything but 80, and http://sub.domain.com if the port is 80.
Special thanks to #torazaburo for mentioning that to me.
You could concatenate the location protocol and the host:
var root = location.protocol + '//' + location.host;
For a url, let say 'http://stackoverflow.com/questions', it will return 'http://stackoverflow.com'
The accepted answer didn't work for me since wanted to be able to work with any arbitary url's, not just the current page URL.
Take a look at the URL object:
var url = new URL("http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah");
url.protocol; // "http:"
url.hostname; // "aaa.bbb.ccc.com"
url.pathname; // "/asdf/asdf/sadf.aspx"
url.search; // "?blah"
Use document.location object and its host or hostname properties.
alert(document.location.hostname); // alerts "stackoverflow.com"
There are two ways. The first is a variant of another answer here, but this one accounts for non-default ports:
function getRootUrl() {
var defaultPorts = {"http:":80,"https:":443};
return window.location.protocol + "//" + window.location.hostname
+ (((window.location.port)
&& (window.location.port != defaultPorts[window.location.protocol]))
? (":"+window.location.port) : "");
}
But I prefer this simpler method (which works with any URI string):
function getRootUrl(url) {
return url.toString().replace(/^(.*\/\/[^\/?#]*).*$/,"$1");
}
Let's suppose you have this url path:
http://localhost:4200/landing?query=1#2
So, you can serve yourself by the location values, as follow:
window.location.hash: "#2"
​
window.location.host: "localhost:4200"
​
window.location.hostname: "localhost"
​
window.location.href: "http://localhost:4200/landing?query=1#2"
​
window.location.origin: "http://localhost:4200"
​
window.location.pathname: "/landing"
​
window.location.port: "4200"
​
window.location.protocol: "http:"
window.location.search: "?query=1"
Now we can conclude you're looking for:
window.location.hostname
Try
document.location.host
or
document.location.hostname
use
window.location.origin
and for: "http://aaa.bbb.ccc.ddd.com/sadf.aspx?blah"
you will get: http://aaa.bbb.ccc.ddd.com/
There is another hack I use and never saw in any StackOverflow response :
using "src" attribute of an image will yield the complete base path of your site.
For instance :
var dummy = new Image;
dummy.src = '$'; // using '' will fail on some browsers
var root = dummy.src.slice(0,-1); // remove trailing '$'
On an URL like http://domain.com/somesite/index.html,
root will be set to http://domain.com/somesite/.
This also works for localhost or any valid base URL.
Note that this will cause a failed HTTP request on the $ dummy image.
You can use an existing image instead to avoid this, with only slight code changes.
Another variant uses a dummy link, with no side effect on HTTP requests :
var dummy = document.createElement ('a');
dummy.href = '';
var root = dummy.href;
I did not test it on every browser, though.
Check this:
alert(window.location.hostname);
this will return host name as www.domain.com
and:
window.location.host
will return domain name with port like www.example.com:80
For complete reference check Mozilla developer site.
I know this is a bit late, but I made a clean little function with a little ES6 syntax
function getHost(href){
return Object.assign(document.createElement('a'), { href }).host;
}
It could also be writen in ES5 like
function getHost(href){
return Object.assign(document.createElement('a'), { href: href }).host;
}
Of course IE doesn't support Object.assign, but in my line of work, that doesn't matter.
I would like to specify something. If someone want to get the whole url with path like I need, can use:
var fullUrl = window.location.protocol + "//" + window.location.hostname + window.location.pathname;
Regex provides much more flexibility.
//document.location.href = "http://aaa.bbb.ccc.com/asdf/asdf/sadf.aspx?blah
//1.
var r = new RegExp(/http:\/\/[^/]+/);
var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com
//2.
var r = new RegExp(/http:\/\/[^/]+\/[^/]+/);
var match = r.exec(document.location.href) //gives http://aaa.bbb.ccc.com/asdf
My solution works in all web browsers including Microsoft Internet Explorer and doesn't use any regular expression, it's inspired of Noah Cardoza and Martin Konecny solutions:
function getHostname(href) {
if (typeof URL === 'object') {
// workaround for MS IE 11 (Noah Cardoza's solution but without using Object.assign())
var dummyNode = document.createElement('a');
dummyNode.href = href;
return dummyNode.hostname;
} else {
// Martin Konecny's solution
return new URL(href).hostname;
}
}
You can split the URL string using /
const exampleURL = "Https://exampleurl.com/page1/etc/etc"
const URLsplit = exampleURL.split("/")
console.log(URLsplit)
console.log(URLsplit[2])
Result. exampleurl.com

Categories

Resources