I'm currently stumped on this. I've snooped around for a bit and haven't found any concrete answer using just JS to do this, and so my question is thus. If I am navigating multiple pages and want to keep query strings from the one before attached to the url, what is the easiest way to do this?
You can do this if the way the user "navigates" is by using links within the pages.
In a given html page, Javascript running within the page can see the url's query parameters via the window.search property. Mozilla docs.
Then use JS to modify all of the page's anchor elements' href links to add on the already existing query parameters to the links.
Result: clicking on a link in the page will result in the new page having both the existing and new query parameters.
I don't think there is an easy way. You will have to take in account the current query parameters every time you compose a URL or create a form.
Are you asking for this one?
var url1 = "...", url2 = "...";
var query1 = url1.split("#")[0].split("?").slice(1).join("?");
if (!query1)
return url2;
var parts2 = url2.split("#");
parts2[0] += (parts2[0].indexOf("?")>-1 ? "&" : "?" ) + query1;
return parts2.join("#");
This extracts the query string from url1 and appends it to the query string of url2, returning the new url2.
Related
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);
}
I am using C# and I have a CMS that uses an open text field. I am doing a redirect manually appending a query string BUT on top of that, I have editors putting UTMs into the URL. I am trying to track the redirects/vanity URLs so we an see the success of them, but the editors are adding UTMs and when I am transferring the redirect, I prepend "?ref=" to their URL to the second URL.
I need to know how to replace any subsequent question marks in the query string.
The CMS is seeing the second question mark and automatically redirecting to the homepage, because I think it is trying to be smart with the URL and the second question mark is causing it to think the URL is invalid.
So the original URL I am getting looks something like this:
www.mysite.com/somepage?utm_source=foo&utm_medium=bar
BUT it then redirects so I can track the URL and it looks now like this
www.myothersite.com/this-other-page?ref=www.mysite.com/somepage?utm_source=foo&utm_medium=bar
So what I want to do is in the second URL is to replace the second question mark with an ampersand. How would I do only the second or subsequent ones without getting rid of the first one?
I am using Javascript to do the redirect in the view.
My code so far
#{
var currentPageUrl = HttpContext.Current.Request.Url.AbsoluteUri;
}
<script type="text/javascript">
setTimeout(function () {
window.location.href = '#Model.Content.GetPropertyValue("externalRedirectURL")?ref=#currentPageUrl';
}, 200); //will call the function after 2 secs
</script>
I found my answer now using HTML.Raw and Json.Ecode.
When I did generic .Replace in the actual Javascript built string, for some reason the .Replace("?", "&") was adding another ampersand to anything in the query string with an ampersand already in the query string. Not what I expected.
Anyways, here is my answer
<script>
var currentP = #Html.Raw(Json.Encode(#currentPageUrl.Replace("?","&")));
setTimeout(function () {
window.location.href = '#Model.Content.GetPropertyValue("externalRedirectURL")' + '?ref=' + currentP;
}, 200); //will call the function after 2 secs
</script>
I am trying to append a query string on a URL to all anchor links on page. If the page URL was www.example.com/page?paramter1=variable¶meter2=variable2
The variables may change each time and it is to be used for analytics.
I would like all the other links on the page to automatically get ?paramter1=variable¶meter2=variable2 added to them when the page loads.
I had been playing around with the following script but i can't seem get variable 'myquerystringtoadd' to be populated by the query string in the URL which I don't necessarily know what the parameters would be so it is the whole query string.
var querystring = 'myquerystringtoadd';
$('a').each(function()
{
var href = $(this).attr('href');
href += (href.match(/\?/) ? '&' : '?') + querystring;
$(this).attr('href', href);
});
Any help would be much appreciated!
How about using querySelectorAll in vanilla javascript instead of jquery. Also, kill your leading '?' in querystring. And if part of your question involves how to get the querystring from the current page's url, use window.location.search.
In the snippet below, you have some google search anchors. One searches 'x', and the other searches 'y'. Your query string further specifies that in both anchors, you want a safe search for images.
// You will use window.location.search
let querystring = '?tbm=isch&safe=active'
if(querystring.startsWith('?'))
querystring = querystring.replace('?', '');
for(let a of document.querySelectorAll('a')) {
a.href +=
(a.href.match(/\?/) ? '&' : '?') +
querystring;
}
<a href='https://www.google.com/search?q=x'>search x images safely</a><br/>
<a href='https://www.google.com/search?q=y'>search y images safely</a>
Note: You may have noticed that I'm editing this question a lot, but it's just to to work with google query strings.
I have some Javascript that parses out the name of a site so that I can query an XML file to pull data where the node's attribute is the last part of a URL.
<script>
function myExampleSite()
{
var myURL = window.location.href;
var dashIndex = myURL.lastIndexOf("-");
var dotIndex = myURL.lastIndexOf(".");
var result = myURL.substring(dashIndex + 1, dotIndex);
return result;
}
var exampleSite = myExampleSite();
</script>
For example, if the site is http://myexamplesite.com/status-Blah00 I would be able to get all data out of the Blah00 XML node and populate various aspects of the site with whatever is in the XML.
This works fine and I am able to use the URL name (Status-Blah00, Status-Blah01, etc.) to query XML against it and populate elements on the page based on the name of the site.
However I ran into problems where a site has a second - in the URL.
For example:
http://myexamplesite.com/status-Blah01-Blah00.htm
It should be parsing the Blah01-Blah00 node of my XML, but instead of just gets the data from Blah00 since it doesn't recognize the first -. I'm new to javascript and I'm confused as to how to basically do:
if 1 "-" in url then get last index
else the number of "-" in url is > 1, get first index.
How would I be able to count the number of "-" in the URL and logically do just that with the above Javascript?
You could use a regex for this problem. Here is a start:
"status-Blah01-Blah00.htm".match(/([^-]+)/g)
That code generates the array:
["status", "Blah01", "Blah00.htm"]
So you can work with the length of that array to find out how many hyphens are in the url.
Even easier: "status-Blah01-Blah00.htm".split('-') returns the same array.
Here is a single line with sequential regexes that can handle dashes occurring elsewhere in the url and that keeps the Blah01-Blah00 node as a single string rather than separating them, as it seems you requested.
"http://www.site-name.com/folder-name/01-10-20/status-Blah0100-Blah01.htm".match(/-([^.\/]+)\.htm/g)[0].match(/[A-z0-9][A-z0-9\-]+/g)[0]
Generates:
"Blah0100-Blah01"
I 'd like to grab the current URL, replace a part of the pathname within it, and open the result in a new tab.
The current URL looks something like this:
http://website.com/file.php?identificator=11111&folder=name
I would like to get the URL (I assume using "window.location" to be most suitable (?)), then replace the parameter "name" (variable, could be different at any time) with "name2" (fixed value) and open resultant URL in a new tab, possibly multiple times.
I've tried looking into replace(), but couldn't get into isolating the parameter inside the pathname.
How would one proceed? jQuery could be a possible replacement too.
Thanks for any help.
<script>
url = window.location.href;
newurl = url.replace(url,"http://website.com/file.php?identificator=11111&folder=anything
"); // your replacement
window.onload = window.open(newurl);
</script>
*untested code