replace certain parameter or entire URL - javascript

I need to replace the window URL with a new one based on a checkbox input. I'm trying to do this like so:
// get checkbox value
var selection = $('input[type="checkbox"]:checked').val()
// get current url
var url = window.location.href;
// prefix current URL with checkbox
url += '&site=' + selection + '&page=1';
// debug line
// console.log(url);
// navigate to new URL
location.replace(url);
I have a series of parameters at the end of my URL that looks like:
mywebsite.com&site=main&page=1
I either need to replace the entire URL, or just the parameters below:
&site=main&page=1
The key is in the last line. I've tried a few things this is the output:
Both location.assign(url); and location.replace(url); gives: mywebsite.com&site=main&page=1&site=main&page=1
window.location.href() seems to have the same behavior, it does not replace the entire URL.
What I don't understand is for location.replace() - sanity checking the behavior on reading MDN, it quotes:
The Location.replace() method replaces the current resource with the
one at the provided URL.
Ok, lets do it. Then this happens:
http://mywebsite.com&site=main&page=1&site=main&page=1
Beating to the punch - in the console log - it returns the correct URL parameters. So output in my console looks like:
http://mywebsite.com&site=main&page=1
Why is it not replacing the entire URL with the new one? How do you just replace the entire URL with a new one, or somehow just target the parameters? Regex?

Why not just build the URL you want and set that?
var url = 'http://mywebsite.com?site=' + selection + '&page=1';
location.href = url;
If you don't know what page you are on and that will be dynamic you can do:
var hostAndPath = location.host + location.pathname;
var selection = $('input[type="checkbox"]:checked').val();
var url = hostAndPath + '?site=' + selection + '&page=1';
location.href = url;

Related

Custom Javascript GTM variable - remove UTMs

I've got a CSJ variable to capture the last parameter of the URL. Given I'm interested on capturing the location and its position may vary (see example below), I managed to create a custom variable that will always give me the last parameter in the URL.
URL examples:
https://www.example.co.nz/location/**holmwood**
https://www.example.co.nz/find-a-location/auckland/**central-auckland**
The issue I'm having is that my script (see below) is not only capturing the last parameter of the URL, but any string after the "?" symbol, which are mainly UTMs.
Code:
function(){
var pageUrl = window.location.href;
return pageUrl.split("/")[pageUrl.split("/").length - 1];
}
So, on my GA view instead of seeing the ph + the location, I see a large string:
I know I could use page path and remove query from there, but for a specific event I'd rather sort that out from the custom variable because of the type of value I'm passing.
What else should I add to my script to keep it completely the same and exclude any query parameters that might be automatically tagged?
Thanks.
Rather than returning the first split, I would then put it through an additional one where you are splitting on the '?'
function(){
var pageUrl = window.location.href;
var lastSlash = pageUrl.split("/")[pageUrl.split("/").length - 1];
return lastSlash.split("?",1);
}

URL location can someone explain?

I am just starting to learn location API(s), such as redirection URL in javascript and I can not understand the following three lines,
Can someone explain me?
let windowUrl = new URLSearchParams(window.location.search);
const queryString = window.location.href;
const firstParam = queryString.substring(queryString.lastIndexOf("?") + 1).split("=")[0];
The first line is useless. As you can see, windowUrl never gets used.
The following two lines:
window.location.href is nothing but the URL that you see in your browser's location bar. Say, https://www.youtube.com/watch?v=123456
so queryString = "https://www.youtube.com/watch?v=123456"
what the 2nd line does is to take everything that comes after "?" in that string. So v=123456
Then, it splits v=123456 by "=" as a separator. So, finally you get 123456.
Now, all of the above is quite barbaric, as you could obtain the value that "v" parameter this way:
let url = new URL(window.location.href);
let v = url.searchParams.get("v");
URL is an interface that will, shall we say "analyze" a URL and give you methods to parse it conveniently, such as the searchParams method, and more.
MDN https://developer.mozilla.org/en-US/docs/Web/API/URL
Description inline the code:
// for Example: https://stackoverflow.com/questions/69835761/js-url-location-can-someone-explain?search=hello
windowUrl = new URLSearchParams(window.location.search);
// URLSearchParams object that helps you to provide data to the query url
// window.location.search will return the current search query from your url
queryString = window.location.href;
// the current url: in this case: https://stackoverflow.com/questions/69835761/js-url-location-can-someone-explain?search=hello
firstParam = queryString.substring(queryString.lastIndexOf("?") + 1).split("=")[0]
// you filter or prase the value from the query string
But you can have it easier, like #resle already wrote.
// get the current url
const uri = new URL(window.location.href);
const quersValue = uri.searchParams.get("search");
// output : hello
let windowUrl = new URLSearchParams(window.location.search) ==> fetching URL params from the url. E.g website.com/?hello=1
const queryString = window.location.href; ===> getting the URL of your current page.
const firstParam = queryString.substring(queryString.lastIndexOf("?") + 1).split("=")[0]; ===> String manipulation to get the first param from the URL. Would open dev tool and play with it, to get the feeling.
E.g:
const x = "https://stackoverflow.com/questions/69835761/js-url-location-can-someone-explain/?hello=1"
const x = "https://stackoverflow.com/questions/69835761/js-url-location-can-someone-explain/?hello=1"
console.log(x)
Result: 'hello'
So here's a breakdown of what the code does:
let windowUrl = new URLSearchParams(window.location.search);
Here an instance of a URLSearchParams object which parses the search (effectively the query string).
const queryString = window.location.href;
This grabs the href (i.e. the entire URL including the query string and hash) and names it queryString (very bad name)
const firstParam = queryString.substring(queryString.lastIndexOf("?") + 1).split("=")[0];
This grabs the variable named "queryString" which is the href and finds the last index of ? which the code author hoped would designate the place where the query string starts (which is not correct). It then does some string manipulation to attempt get the first query string parameter key which would probably work for most cases but not all.
This code can be greatly simplified to:
const firstParam = (new URL(window.location.href)).searchParams.keys()?.[0];
This will use the JS URL class to parse the URL correctly and get the first key of the search parameters. ?.[0] is the optional chaining operator for arrays
Note that the 3rd line is wrong in this case because a URL like https://example.com/test?param=a&other=b&param=c#hashwith?questionmark
is valid but the code will think the first URL parameter is questionmark instead of param which would be the expected answer.

Most efficient way to replace/add certain URL query string parameters? Minimize load time/redirects

We use three query strings that are pulled into form fields before a user submits. src, cst, and cid are the three parameters. cid and cst always need to be updated to the correct value. src will vary, but if none exists on the URL it should add a default one. I have this working, but think there has to be a much quicker, easier, faster way to do all of this.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var src = "Report";
var cid = "7013475893xfvg";
var cst = "Responded";
var vsrc = "src";
var vcid = "cid";
var vcst = "cst";
var srcstring = "&" + vsrc + "=" + src;
if ('URLSearchParams' in window) {
var searchParams = new URLSearchParams(window.location.search)
searchParams.set(vcid, cid);
searchParams.set(vcst, cst);
var newRelativePathQuery = window.location.pathname + '?' + searchParams.toString();
history.pushState(null, '', newRelativePathQuery);
}
if (!(window.location.href.indexOf(vsrc) > -1)) {
window.location.search += srcstring;
}
</script>
First, the script adds or updates the cid and cst values to the correct ones defined in the variable. Then, the script determines whether "src" is present in the address bar. If it's not present, it adds the src parameter with a default value.
The goal is for this to be limited to at most one redirect, or history record. Ideally, the user will never see a reload, redirect take place and will not be present in their history. This works currently on Google Chrome desktop, but on Safari Mobile history records are created.
Edit: We discovered an issue with this code that also prevents form fields from gathering values if "%20" is any where in the URL. %20 gets converted to a "+" and breaks this process. How can we avoid this?

How do I extract the domain with a hash?

I want to extract the domain with a hash without the long random id from the location address bar to make it to show like this:
http://test.example.com/#inbox
Here is the full URL:
http://test.example.com/#inbox/U2FsdGVkX19stSSdMXLZq5v7bOgzRLtaM7Lr1t+lWpI=
Here is what I have tried so far:
var url = location.hash.split('#inbox')[1];
And I have also tried this:
var url = $(location).attr("href").split('/')[2];
Unfortunately, I didn't get what I want to extract the domain and the hash without the long random id.
When I try it, it extracts the domain name and the hash without the random id to get the return output for the URL like http://test.example.com/#inbox.
I would use indexOf() to find the position of the '#' character. Since the URL can't include a '#', it is safe to assume that the first '#' will be the one you're interested in.
Then I would search for the '/', again with indexOf(), so the word between the '#' and the '/' can change and things still work as expected.
That position is the location of the '/' and anything before that can be returned which is what the String.sub() function does and it returns that URL you're looking for:
var pos = location.href.indexOf('#')
pos = location.href.indexOf('/', pos)
var url = location.href.substr(0, pos)
Another way, although I'm not sure whether it's fully portable, is to use the location fields like so:
var url = location.origin + location.pathname + "#inbox"
If the "#inbox" part can change, you may be able to tweak the code or search for a slash in location.hash like so:
var pos = location.hash.indexOf('/')
var url = location.origin + location.pathname + location.hash.sub(0, pos)
Either way should be plenty fast anyway (especially since you won't need to loop over such).
I got the whole URL, found where the "#" is, added 6 to its count for "#" + the word "inbox", and dropped the rest of the URL:
var url = document.URL;
var i = url.indexOf('#') + 6; // 6 is length of "#" + the word "inbox"
var answer = url.substr(0, i);
Try the code below:
// Complete URL
var url = 'http://test.example.com/#inbox/U2FsdGVkX19stSSdMXLZq5v7bOgzRLtaM7Lr1t+lWpI=';
var desiredResult = url.match(/.*\/\#inbox\//)[0];
console.log(desiredResult.substring(0, desiredResult.length - 1)); // this will output 'http://test.example.com/#inbox'

spliturl function appending twice

here's the code:
function chatWin(url,name){
var nw;
var splitUrlResults = url.split("#");
url = appendDataWakeNVPs(splitUrlResults[0]) + '#' + splitUrlResults[1] ;
nw=window.open(url,name,"height=600,width=433,left=100,top=100,resizable=yes,scrollbars=no,toolbar=no,status=no");
if (nw.focus) {nw.focus();}
}
and then the link in the code:
PROD_TAB_EXPRT_LNK_EMAIL=javascript:chatWin('/customerService/contactUs/help.html#1','Help')
but the rendered code is:
<a href="javascript:chatWin('/customerService/contactUs/help.html#0#1','Help');">
Every link is getting #0 appended before the tab identifier- (#1 in this case).
thoughts?
It looks to me like the only way url ends up with #0#1 on the end of it is if appendDataWakeNVP() is appending #0 onto it's return value and your code is then adding the #1 onto the end of that.
So, I think your problem is in appendDataWakeNVP(). I'd suggest stepping into that function in your favorite debugger and you can discover what it does. Or grep for it in your source tree and examine it in your editor. If it's suppose to add #0 onto the end and you can't change that, but you don't want that there, then you will have to remove that before appending your own hash onto the end of it.
Any hash value you don't want can be removed with this:
url = url.replace(/#.*$/, "");
So, you could change this line of code:
url = appendDataWakeNVPs(splitUrlResults[0]) + '#' + splitUrlResults[1] ;
to this:
url = appendDataWakeNVPs(splitUrlResults[0]).replace(/#.*$/, "") + '#' + splitUrlResults[1] ;

Categories

Resources