How to get url path without $_GET parameters using javascript? - javascript

If my current page is in this format...
http://www.mydomain.com/folder/mypage.php?param=value
Is there an easy way to get this
http://www.mydomain.com/folder/mypage.php
using javascript?

Don't do this regex and splitting stuff. Use the browser's built-in URL parser.
window.location.origin + window.location.pathname
And if you need to parse a URL that isn't the current page:
var url = document.createElement('a');
url.href = "http://www.example.com/some/path?name=value#anchor";
console.log(url.origin + url.pathname);
And to support IE (because IE doesn't have location.origin):
location.protocol + '//' + location.host + location.pathname;
(Inspiration from https://stackoverflow.com/a/6168370/711902)

Try to use split like
var url = "http://www.mydomain.com/folder/mypage.php?param=value";
var url_array = url.split("?");
alert(url_array[0]); //Alerts http://www.mydomain.com/folder/mypage.php
Even we have many parameters in the GET , the first segment will be the URL without GET parameters.
This is DEMO

try this:
var url=document.location.href;
var mainurl=url.split("?");
alert(mainurl[0]);

Try
var result = yourUrl.substring(0, yourUrl.indexOf('?'));
Working demo

var options = decodeURIComponent(window.location.search.slice(1))
.split('&')
.reduce(function _reduce (/*Object*/ a, /*String*/ b) {
b = b.split('=');
a[b[0]] = b[1];
return a;
}, {});

Related

Add "/path/" in the middle of an URL in JavaScript

How can I effectively add a "path" to the middle of an URL in JavaScript?
I want to add embed to an URL, so the URL https://blog.com/post/123 will end up looking like this https://blog.com/embed/post/123?
Cheers
You can create an <a> and set the href property. Then prepend embed to the pathname and use toString() to get the whole URL.
let element = document.createElement('a');
element.href = 'https://blog.com/post/123';
element.pathname = 'embed' + element.pathname;
console.log(element.toString());
You can do this, if the path is just a string
var path = "https://blog.com/post/123";
var withEmbed = path.replace(/\/post\//,'/embed/post/');
console.log(withEmbed);
You can use the location API.
https://developer.mozilla.org/en-US/docs/Web/API/Location
function addEmbed(location) {
return location.protocol + '//' + location.host +
'/embed' + location.pathname;
}
var url = document.createElement('a');
url.href = 'https://blog.com/post/123';
var embed = addEmbed(url);
console.log(embed); // "https://blog.com/embed/post/123"
Example: https://codepen.io/anon/pen/wXxvaq
The way i would do it, is to pass by ref/value the original URL and the text you wan to add, into a function. It then removes the "https://" (if necessary), splits the url at the first "/" and saves each part as a var. Finally it puts it all back together and outputs it to a on the html page.
This doesnt have to be outputted in this way, it could be saved as a global variable and then used in a link (but i didn't know what your plan was so i outputted it) :)
function addToURL(URL, add) {
URL = URL.replace(/(^\w+:|^)\/\//, '');
var part1 = URL.substring(0, URL.indexOf("/") + 1);
var part2 = URL.substring(URL.indexOf("/"), URL.length);
var result = "https://" + part1 + add + part2;
document.getElementById("demo").innerHTML = result;
}
Here's the example I made: https://codepen.io/anon/pen/RJBwZp
Hope this helps :P

Replace the url parameter value using js

I have a URL like below.
something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false
I want to replace the value of parameter showHiddenElements to some new value.
for e.g. exising value in URL -> showHiddenElements=false
I want to change it through JavaScript to -> showHiddenElements=true
Please advise.
Edit:
showHiddenElements may not always be false. And In some cases it may not be available.
Use the URL Object:
const url = new URL('http://something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false');
url.searchParams.delete('showHiddenElements');
url.searchParams.append('showHiddenElements', true);
So you just delete the parameter and update it with the new one (not the most elegant)
Docs here: https://developer.mozilla.org/fr/docs/Web/API/URL
You could use String.replace for that:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
newUrl = url.replace('showHiddenElements=false', 'showHiddenElements=true');
You could also do it fancy and use regex:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
newUrl = url.replace(/showHiddenElements=false$/, 'showHiddenElements=true');
The regex would only match showHiddenElements=false if it's on the end of the URL
To see if it's available you could use regex too:
var url = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
// If the url doesn't have a showHiddenElements=__any_word__
if (!url.match(/showHiddenElements=\w+/)) {
url = url + 'showHiddenElements=false';
}
var url = "something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false";
alert("Before: "+url);
url = url.replace("&showHiddenElements=false","&showHiddenElements=true");
alert("After: "+url);
//Console.log clips the end so we can't see the result :(
Maybe something liket this:
var loc = window.location.href;
var newLoc = loc.Replace('showHiddenElements=true', 'showHiddenElements=false')
A JavaScript Regular Expression should help if you are just treating the URL as a string.
var str = 'something.com/TaskHandler/search.do?action=search&category=basic&page=1&sortBy=NAME&Ascending=true&showHiddenElements=false';
var res = str.replace(/showHiddenElements/i, 'true');
console.log(res);

Javascript location.pathname returns querysting [duplicate]

I have a URL like http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235.
I want to get the URL without the query string: http://localhost/dms/mduserSecurity/UIL/index.php.
Is there any method for this in JavaScript? Currently I am using document.location.href, but it returns the complete URL.
Try this:
let path = window.location.href.split('?')[0]
console.log({path})
Read about Window.location and the Location interface:
const urlPieces = [location.protocol, '//', location.host, location.pathname]
let url = urlPieces.join('')
console.log({urlPieces, url})
location.toString().replace(location.search, "")
var url = window.location.origin + window.location.pathname;
If you also want to remove hash, try this one: window.location.href.split(/[?#]/)[0]
Here's an approach using the URL() interface:
new URL(location.pathname, location.href).href
Try:
document.location.protocol + '//' +
document.location.host +
document.location.pathname;
(NB: .host rather than .hostname so that the port gets included too, if necessary)
To get every part of the URL except for the query:
var url = (location.origin).concat(location.pathname).concat(location.hash);
Note that this includes the hash as well, if there is one (I'm aware there's no hash in your example URL, but I included that aspect for completeness). To eliminate the hash, simply exclude .concat(location.hash).
It's better practice to use concat to join Javascript strings together (rather than +): in some situations it avoids problems such as type confusion.
just cut the string using split (the easy way):
var myString = "http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235"
var mySplitResult = myString.split("?");
alert(mySplitResult[0]);
Use properties of window.location
var loc = window.location;
var withoutQuery = loc.hostname + loc.pathname;
var includingProtocol = loc.protocol + "//" + loc.hostname + loc.pathname;
You can see more properties at https://developer.mozilla.org/en/DOM/window.location
How about this: location.href.slice(0, - ((location.search + location.hash).length))
Here are two methods:
<script type="text/javascript">
var s="http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu
=true&pcode=1235";
var st=s.substring(0, s.indexOf("?"));
alert(st);
alert(s.replace(/\?.*/,''));
</script>
You could make use of the URL constructor like this:
const href = 'http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235'; // document.location.href
const url = new URL(href);
const noSearchUrl = href.replace(url.search, '');
console.log(noSearchUrl);
Just add these two lines to $(document).ready in JS as follow:
$(document).ready(function () {
$("div.sidebar nav a").removeClass("active");
$('nav a[href$="'+ window.location.pathname.split("?")[0] +'"]').addClass('active');
});
it is better to use the dollar sign ($) (End with)
$('nav a[href$
instead of (^) (Start with)
$('nav a[href^
because, if you use the (^) sign and you have nested URLs in the navigation menu, (e.g "/account" and "/account/roles")
It will active both of them.
window.location.href.split("#")[0].split("?")[0]
You can create instance of URL and then clear the query string:
const url = new URL(document.location.href);
url.search = '';
console.log(url.href);
If you are using navigation bar and want to get the pure url after clicking on the side bar navigation, then the following code might be helpful:
$(document).ready(function () {
$("div.sidebar nav a").removeClass("active");
var urlPath = window.location.pathname.split("?")[0];
var nav = $('div.sidebar nav a').filter(function () {
return $(this).attr('href').toLowerCase().indexOf(urlPath.toLocaleLowerCase()) > -1;
});
$(nav).each(function () {
if ($(this).attr("href").toLowerCase() == urlPath.toLocaleLowerCase())
$(this).addClass('active');
});
});

FileName from url excluding querystring

I have a url :
http://www.xyz.com/a/test.jsp?a=b&c=d
How do I get test.jsp of it ?
This should do it:
var path = document.location.pathname,
file = path.substr(path.lastIndexOf('/'));
Reference: document.location, substr, lastIndexOf
I wont just show you the answer, but I'll give you direction to it. First... strip out everything after the "?" by using a string utility and location.href.status (that will give you the querystring). Then what you will be left with will be the URL; get everything after the last "/" (hint: lastindexof).
Use a regular expression.
var urlVal = 'http://www.xyz.com/a/test.jsp?a=b&c=d';
var result = /a\/(.*)\?/.exec(urlVal)[1]
the regex returns an array, use [1] to get the test.jsp
This method does not depend on pathname:
<script>
var url = 'http://www.xyz.com/a/test.jsp?a=b&c=d';
var file_with_parameters = url.substr(url.lastIndexOf('/') + 1);
var file = file_with_parameters.substr(0, file_with_parameters.lastIndexOf('?'));
// file now contains "test.jsp"
</script>
var your_link = "http://www.xyz.com/a/test.jsp?a=b&c=d";
// strip the query from the link
your_link = your_link.split("?");
your_link = your_link[0];
// get the the test.jsp or whatever is there
var the_part_you_want = your_link.substring(your_link.lastIndexOf("/")+1);
Try this:
/\/([^/]+)$/.exec(window.location.pathname)[1]

Is there any method to get the URL without query string?

I have a URL like http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235.
I want to get the URL without the query string: http://localhost/dms/mduserSecurity/UIL/index.php.
Is there any method for this in JavaScript? Currently I am using document.location.href, but it returns the complete URL.
Try this:
let path = window.location.href.split('?')[0]
console.log({path})
Read about Window.location and the Location interface:
const urlPieces = [location.protocol, '//', location.host, location.pathname]
let url = urlPieces.join('')
console.log({urlPieces, url})
location.toString().replace(location.search, "")
var url = window.location.origin + window.location.pathname;
If you also want to remove hash, try this one: window.location.href.split(/[?#]/)[0]
Here's an approach using the URL() interface:
new URL(location.pathname, location.href).href
Try:
document.location.protocol + '//' +
document.location.host +
document.location.pathname;
(NB: .host rather than .hostname so that the port gets included too, if necessary)
To get every part of the URL except for the query:
var url = (location.origin).concat(location.pathname).concat(location.hash);
Note that this includes the hash as well, if there is one (I'm aware there's no hash in your example URL, but I included that aspect for completeness). To eliminate the hash, simply exclude .concat(location.hash).
It's better practice to use concat to join Javascript strings together (rather than +): in some situations it avoids problems such as type confusion.
just cut the string using split (the easy way):
var myString = "http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235"
var mySplitResult = myString.split("?");
alert(mySplitResult[0]);
Use properties of window.location
var loc = window.location;
var withoutQuery = loc.hostname + loc.pathname;
var includingProtocol = loc.protocol + "//" + loc.hostname + loc.pathname;
You can see more properties at https://developer.mozilla.org/en/DOM/window.location
How about this: location.href.slice(0, - ((location.search + location.hash).length))
Here are two methods:
<script type="text/javascript">
var s="http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu
=true&pcode=1235";
var st=s.substring(0, s.indexOf("?"));
alert(st);
alert(s.replace(/\?.*/,''));
</script>
You could make use of the URL constructor like this:
const href = 'http://localhost/dms/mduserSecurity/UIL/index.php?menu=true&submenu=true&pcode=1235'; // document.location.href
const url = new URL(href);
const noSearchUrl = href.replace(url.search, '');
console.log(noSearchUrl);
Just add these two lines to $(document).ready in JS as follow:
$(document).ready(function () {
$("div.sidebar nav a").removeClass("active");
$('nav a[href$="'+ window.location.pathname.split("?")[0] +'"]').addClass('active');
});
it is better to use the dollar sign ($) (End with)
$('nav a[href$
instead of (^) (Start with)
$('nav a[href^
because, if you use the (^) sign and you have nested URLs in the navigation menu, (e.g "/account" and "/account/roles")
It will active both of them.
window.location.href.split("#")[0].split("?")[0]
You can create instance of URL and then clear the query string:
const url = new URL(document.location.href);
url.search = '';
console.log(url.href);
If you are using navigation bar and want to get the pure url after clicking on the side bar navigation, then the following code might be helpful:
$(document).ready(function () {
$("div.sidebar nav a").removeClass("active");
var urlPath = window.location.pathname.split("?")[0];
var nav = $('div.sidebar nav a').filter(function () {
return $(this).attr('href').toLowerCase().indexOf(urlPath.toLocaleLowerCase()) > -1;
});
$(nav).each(function () {
if ($(this).attr("href").toLowerCase() == urlPath.toLocaleLowerCase())
$(this).addClass('active');
});
});

Categories

Resources