Add a class to an object using javascript for specific querystring - javascript

I want to use javascript or jquery to add a class to an object based on the URL query string.
So if the url is example.com/?var=1 then I want to add a new class to the object
#mydiv
This would then be repeated for ?var=2, ?var=3 and so on.
Here is what I have tried. The hope for this is that it would add a different class to the object if the query string was either ?var=2 or?var=3
var queryString = window.location.search.substr(1);
switch (queryString) {
case "2": document.getElementById('mydiv').className = 'newclass2';
;
break;
case "3": document.getElementById('mydiv').className = 'newclass2';
;
break;
}
EDIT:
It almost works now....
Here is my current code:
<script>
var queryString = window.location.search.substr(1);
var variant = queryString.split('=')[1];
switch(variant) {
case "stnl2": document.getElementById('getexclusive-sb').className = 'stnlvar2';
;
break;
case "stnl3": document.getElementById('getexclusive-sb').className = 'stnlvar3';
;
break;
}
</script>
It works if the url is "/?v=stnl2"
However Google content adds more to the url such as "?v=stnl2&utm_expid=42387987-0.dmsadhasjkdjasgdjgas-Q.4"
Is there a way for me to ignore the & and all details after so my code still works?

var getUrlVars = function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
if(vars[0] == window.location.href){
vars =[];
}
return vars;
}
var params = getUrlVars();
switch (params['var']){
...
}
Your params will have all the parameters from your query string. just past the variable name as a string and you will get the value of that parameter.

The solution you tried has two issues.
First, you are getting the number of variant incorrectly. With your code, queryString will be like "var=2". So if you want only number, you should also split it by =:
var queryString = window.location.search.substr(1);
var variant = queryString.split('=')[1];
switch(variant) {
// ...
}
Note that this still actually doesn't check the name of your parameter, i.e. var=. If it is the only parameter, it would work. Otherwise, for proper handling of query string in JS you might want to look at this question
Second, look attentively into your switch. Both branches are actually identical, so they would do exactly the same regardless of queryString. Seems like you copy-pasted it unintentionally.
UPD:
As a said in my original answer, I just pointed you to some issues in your solution and how to fix them. It would not work if there is more than one parameter. Of course, you can just ignore all the string after &. But still there would be many cases in which it still won't work: what if your parameter is not the first?
I think it is not a good idea to make such assumptions, so we come to what I said previously: you might need proper, full-fledged parsing of parameters. The link that I mentioned provides A LOT of solutions for this particular task, you may choose any of them. Another option is to use some existing library which have such function provided. That question and some other SO questions pointed me to these two:
jquery.parsequery — a jQuery plugin for this only purpose, with which you can do variant = $.query(location).get("paramName"). Seems to be old and not updated.
jsurl — a library for making different things with URLs, in particular, you can do variant = (new Url).query.paramName with it.
NB: (replace paramName with your actual parameter name, v or var or whatever)
Of course there could be some other good libs for it, also try googling on your own.

Related

Regex for url line [duplicate]

This should be very simple (when you know the answer). From this question
I want to give the posted solution a try. My question is:
How to get the parameter value of a given URL using JavaScript regular expressions?
I have:
http://www.youtube.com/watch?v=Ahg6qcgoay4
I need:
Ahg6qcgoay4
I tried:
http://www.youtube.com/watch\\?v=(w{11})
But: I suck...
You almost had it, just need to escape special regex chars:
regex = /http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/;
url = 'http://www.youtube.com/watch?v=Ahg6qcgoay4';
id = url.match(regex)[1]; // id = 'Ahg6qcgoay4'
Edit: Fix for regex by soupagain.
Why dont you take the string and split it
Example on the url
var url = "http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk"
you can do a split as
var params = url.split("?")[1].split("&");
You will get array of strings with params as name value pairs with "=" as the delimiter.
Not tested but this should work:
/\?v=([a-z0-9\-]+)\&?/i
v is a query parameter, technically you need to consider cases ala: http://www.youtube.com/watch?p=DB852818BF378DAC&v=1q-k-uN73Gk
In .NET I would recommend to use System.Web.HttpUtility.ParseQueryString
HttpUtility.ParseQueryString(url)["v"];
And you don't even need to check the key, as it will return null if the key is not in the collection.
I know the question is Old and already answered but this can also be a solution
\b[\w-]+$
and I checked these two URLs
http://www.youtube.com/watch?v=Ahg6qcgoay4
https://www.youtube.com/watch?v=22hUHCr-Tos
DEMO
I use seperate custom functions which gets all URL Parameters and URL parts .
For URL parameters, (which is the final part of an URI String, http://domain.tld/urlpart/?x=a&y=b
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
The above function will return an array consisting of url variables.
For URL Parts or functions, (which is http://domain.tld/urlpart/?x=a&y=b
I use a simple uri split,
function getUrlParams() {
var vars = {};
var parts = window.location.href.split('/' );
return parts;
}
You can even combine them both to be able to use with a single call in a page or in javascript.

How do I force browser not to convert 'comma' to 2C symbols using JS?

I'm changing current user's path through a function:
function setSomeValue(someValues) {
var query = '';
for (var i = 0; i < someValues.length; i++) {
query += someValues[i] + ',';
}
if ('URLSearchParams' in window) {
var searchParams = new URLSearchParams(window.location.search);
searchParams.set("paramName", query);
var newRelativePathQuery = window.location.pathname + '?' + searchParams.toString();
history.pushState(null, '', newRelativePathQuery);
}
}
As you can see, I'm adding to user's location new words and want new location to be like this:
www.site.com?paramName=value1,value2,
But browser converts my commas into %2C so I get this:
www.site.com?paramName=value1%2Cvalue2%2C
What should be done to make pushing commas to URL possible?
(copy & paste from several comments)
It might be due to URLSearchParams and its toString method implementation - but we can’t know, because you have not shown us what that actually is. If that is not deliberately encoding the comma, and the browser simply does it automatically - then there’s little you can do about that.
If newRelativePathQuery contains the encoded versions already, maybe they could be replaced back to normal commas. But if history.pushState does it, then “other ways” to create the URL itself won’t help you much.
Since a debug output showed that newRelativePathQuery contains the encoded commas already, you can try and replace them back to commas, and see if that “survives” being pushed to the history then.
It's a little hacky, but here's one solution. Let's say we want to use URL's searchParams.set() to set ids=1,2,3,4 in our query string.
If you just do url.searchParams.set("ids", "1,2,3,4"), the URL will have ids=1%2C2%2C3%2C4. To avoid that encoding, first set ids=LIST_OF_IDS_PLACEHOLDER, get the URL as a string, and then replace LIST_OF_IDS_PLACEHOLDER with 1,2,3,4, like this:
const myList = [1,2,3,4],
url = new URL(document.location.href); // or however you get your URL object
url.searchParams.set("ids", "LIST_OF_IDS_PLACEHOLDER");
const newUrlString = url.toString().replace("LIST_OF_IDS_PLACEHOLDER", ids.join(','));
console.log(newUrlString); // this will include: ids=1,2,3,4

Passing URL Parameters in href Link

I’m a bit new to this JS stuff and have been surfing and surfing and reading up as much as I can, but I got stumped on this one issue.
I have a website that may contain parameters in the URL. A parameter named “who” to be exact.
If a user comes to the site and their url is http://example.com/?who=123, I want them to be able to click a href link and their parameter get carried on. So if the link goes to http://anotherexample.com, I’d want the link to contain the user’s parameter as well. http://anotherexample.com/?who=123.
What’s the best way to accomplish this? It only needs to be on one of the links, so no concerns about getting the whole site to pass on the parameter.
Thanks!
Would this suffice for you?
Source: https://css-tricks.com/snippets/javascript/get-url-variables/
var svalue=location.search.match(new RegExp("[\?\&]" + "who" + "=([^\&]*)(\&?)","i"));
yourelement.href=yourelement.href+(svalue?svalue[0]:"");
Here is one way you can do it in javascript
first when the document loads write a function in your js to get the parameters from the url
function getparms(variable)
{
let item = window.location.search.substring(1);
let vars = item.split("&");
for (let i=0;i< vars.length;i++) {
let pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
This function would return the following from a url
http://www.somesite.com/index.html?who=100&location=2
Calling getparams('who') would return "100"
So you would call it as:
let myParam = getparams('id');
You can build the url in a new function and navigate to it as:
function goToUrl(urlParam){
let hostAddress= 'yourwebsiteaddress';
let url = "http://" + hostAddress "/?=who" + urlParam;
//go to address
window.location.href = url;
}
which would be called as goToUrl(myParam);
*Disclaimer: I wrote this on the fly so it may not be 100% syntactically correct but it should be accurate enough as pseudo code to help you accomplish what you want.
You talked about href, so I assume all links are set with <a> tag.
There are many options to do that, I'll show you the easiest and cleanest one.
So, assuming the current URL is http://www.example.com/?who=123.
var who = window.location.href.split('?')[1]; // Get `?who=123` from current url
var a = document.getElementsByTagName('a'); // Get all `<a>`
var href;
// Loop through all `<a>`
for (var i = 0; i < a.length; i++){
// Add `?who=123` to all hrefs found.
a[i].href += who;
}
You can freely change document.getElementsByTagName('a') to document.getElementById() to suit your needs.

Change the pathname in the URL of a link while keeping the querystring constant

From a page with the following URL, http://example.com/foo.html?query=1&other=2, I want to create a link to http://example.com/bar.html?query=1&other=2. How do I do that without explicitly saving and reloading all the query strings.
I need this to easily link from an iframe version of a page (embed.html?query) to the full page (index.html?query).
I would have recommended using the Location object's search method (available at document.location or window.location) to pull out the parameters, then modify the rest of the URL, but that API is apparently specific to Firefox.
I would simplify #DMortensen's answer by just splitting on the first ?, then modifying the first part (which will be the URL's path portion only), and reapplying the second part.
If you need to parse the parameters, I recommend the jQuery plugin Query Parameter Parser: one call to $.parseQuery(s) will pull out an object of all the keys & values.
It can be finicky, but you could split the URI on '?' and then loop through the 2nd element of that array to grab the key/val pairs if you need to evaluate each pair (using '&' as a delimiter). The obvious weakness in this would be if there are additional '?' or '&' used in the URI.
Something like this maybe? (pseudocode-ish)
var URI = document.URL;
var qs = URI.split('?');
var keyvalpair = qs[1].split('&');
var reconstructedURI = '&' + keyvalpair;
for(var i = 0; i< keyvalpair.length; i++){
var key = keyvalpair[i].split('=')[0];
var val = keyvalpair[i].split('=')[1];
}
Thank you for all the answers. I tried the following and it works.
function gotoFullSite() {
var search = window.location.search;
window.open("http://example.com/"+search)
}
$('#clickable').click(gotoFullSite);
and then use <a id = "clickable" href="#"></a>. When I click the link, it opens the proper website with all the query parameters in a new tab. (I need a new tab to break out of an iframe.)

Strip Base64-encoded URL parameters with Javascript

I'm decoding my URL parameters in .NET as explained in this article.
In some cases I need to get the URL parameters in Javascript. But the problem is that some parameter values end at a '='.
Example: ?itemID=Jj1TI9KmB74=&cat=1
Javascript function:
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;}
I know my problem is at the split-function in the for-loop but I don't know how to solve it.
I also used jsuri for this but the problem still exists.
Can I solve this in Javascript or do I need to reconsider my encryption-method?
Having an unencoded = in the URL is invalid. To do this right, you would have to additionally apply encodeURIComponent() on the base64 encoded data.
Whether the base64 encoding still makes sense then, is for you to decide.
Reference: RFC 3986: Reserved characters
Having = unencoded in the URI query is invalid. You should escape it. However, for completeness, if you really needed to do this, try this:
Extra note: if you escaped the = using URI encoding, on the server side (e.g. $_GET) it'll be automatically decoded. With JavaScript and location, however, you must decode it first (decodeURIComponent) to work with it.
Instead of doing:
hash = hashes[i].split('=');
where subsequent equals signs are split too, do this instead (a non-greedy match before the first equals symbol for the key name, the rest for the value):
match = hashes[i].match(/([^=]+?)=(.+)/);
key = match[1];
value = match[2];
I assume you can't control the process generating the =s? As Pekka said it's wrong.
However you could manually break the string at the first =, e.g.
var i = hashes[i].indexof('=');
if (i > 0)
{
var key = hashes[i].substring(0,i);
vars.push(key);
if ((i+1) < hashes[i].length)
{
vars[key] = hashes[i].substring(i+1);
}
}
else
{
// No value
vars.push(hashes[i]);
}

Categories