How to check presence of a URL parameter compared to an Array? - javascript

Given these two sample urls and code. How can I use the Array as a reference to check if the values are in the UTM parameter? (There will ONLY be one utm parameter at any given time).
example.com?utm=test
example.com?utm=test2
var partnerArray = ["test", 'test2'];
function findPartner() {
if window.location.href.indexOf('?utm='(partnerArray)' !== -1) {
//do something fun here
}
I know my code is wrong - I haven't found example of using an Array to check for values in the URL.
Thank you.

Let's split this into two problems. First, getting the value of the utm parameter:
function getUTM() {
return new URLSearchParams(window.location.search).get("utm");
}
Then, figuring out whether it's one of the known partners, and returning the one it might be.
const partnerArray = ["test", 'test2'];
function getPartner() {
const utm = getUTM();
return partnerArray.find(partner => partner === utm);
}
getPartner() will return undefined if the query string's utm parameter doesn't match either known partner.

Thanks all those that gave input. Here's my solution for future readers with parts from the comments.
1st: Establish an Array:
var partnerArray1 = ["test1", 'test2'];
var partnerArray2 = ["test3", 'test4'];
2nd: Check what is in the URL's UTM parameter value
var urlParams = new URLSearchParams(window.location.search).get("utm");
3rd: Make a function to check the value against the Array:
function checkUTM() {
if (partnerArray1.indexOf(urlParams) !== -1){
//do some cool stuff here
}
if (partnerArray2.indexOf(urlParams) !== -1){
//do some more cool stuff here
}
}
Short of figuring out how to pass values into the function and check that, I went with the slightly more messy way, but it accomplished my goal. If there are improvements to the above, please feel free to provide clear updated samples.

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.

URL Parse Exercise (JavaScript)

So here is a description of the problem that I've been talked to solve:
We need some logic that extracts the variable parts of a url into a hash. The keys
of the extract hash will be the "names" of the variable parts of a url, and the
values of the hash will be the values. We will be supplied with:
A url format string, which describes the format of a url. A url format string
can contain constant parts and variable parts, in any order, where "parts"
of a url are separated with "/". All variable parts begin with a colon. Here is
an example of such a url format string:
'/:version/api/:collection/:id'
A particular url instance that is guaranteed to have the format given by
the url format string. It may also contain url parameters. For example,
given the example url format string above, the url instance might be:
'/6/api/listings/3?sort=desc&limit=10'
Given this example url format string and url instance, the hash we want that
maps all the variable parts of the url instance to their values would look like this:
{
version: 6,
collection: 'listings',
id: 3,
sort: 'desc',
limit: 10
}
So I technically have a semi-working solution to this but, my questions are:
Am I understanding the task correctly? I'm not sure if I'm supposed to be dealing with two inputs (URL format string and URL instance) or if I'm just supposed to be working with one URL as a whole. (my solution takes two separate inputs)
In my solution, I keep reusing the split() method to chunk the array/s down and it feels a little repetitive. Is there a better way to do this?
If anyone can help me understand this challenge better and/or help me clean up my solution, it would be greatly appreciated!
Here is my JS:
const obj = {};
function parseUrl(str1, str2) {
const keyArr = [];
const valArr = [];
const splitStr1 = str1.split("/");
const splitStr2 = str2.split("?");
let val1 = splitStr2[0].split("/");
let val2 = splitStr2[1].split("&");
splitStr1.forEach((i) => {
keyArr.push(i);
});
val1.forEach((i) => {
valArr.push(i);
});
val2.forEach((i) => {
keyArr.push(i.split("=")[0]);
valArr.push(i.split("=")[1]);
});
for (let i = 0; i < keyArr.length; i++) {
if (keyArr[i] !== "" && valArr[i] !== "") {
obj[keyArr[i]] = valArr[i];
}
}
return obj;
};
console.log(parseUrl('/:version/api/:collection/:id', '/6/api/listings/3?sort=desc&limit=10'));
And here is a link to my codepen so you can see my output in the console:
https://codepen.io/TOOTCODER/pen/yLabpBo?editors=0012
Am I understanding the task correctly? I'm not sure if I'm supposed to
be dealing with two inputs (URL format string and URL instance) or if
I'm just supposed to be working with one URL as a whole. (my solution
takes two separate inputs)
Yes, your understanding of the problem seems correct to me. What this task seems to be asking you to do is implement a route parameter and a query string parser. These often come up when you want to extract data from part of the URL on the server-side (although you don't usually need to implement this logic your self). Do keep in mind though, you only want to get the path parameters if they have a : in front of them (currently you're retrieving all values for all), not all parameters (eg: api in your answer should be excluded from the object (ie: hash)).
In my solution, I keep reusing the split() method to chunk the array/s
down and it feels a little repetitive. Is there a better way to do
this?
The number of .split() methods that you have may seem like a lot, but each of them is serving its own purpose of extracting the data required. You can, however, change your code to make use of other array methods such as .map(), .filter() etc. to cut your code down a little. The below code also considers the case when no query string (ie: ?key=value) is provided:
function parseQuery(queryString) {
return queryString.split("&").map(qParam => qParam.split("="));
}
function parseUrl(str1, str2) {
const keys = str1.split("/")
.map((key, idx) => [key.replace(":", ""), idx, key.charAt(0) === ":"])
.filter(([,,keep]) => keep);
const [path, query = ""] = str2.split("?");
const pathParts = path.split("/");
const entries = keys.map(([key, idx]) => [key, pathParts[idx]]);
return Object.fromEntries(query ? [...entries, ...parseQuery(query)] : entries);
}
console.log(parseUrl('/:version/api/:collection/:id', '/6/api/listings/3?sort=desc&limit=10'));
It would be even better if you don't have to re-invent the wheel, and instead make use of the URL constructor, which will allow you to extract the required information from your URLs more easily, such as the search parameters, this, however, requires that both strings are valid URLs:
function parseUrl(str1, str2) {
const {pathname, searchParams} = new URL(str2);
const keys = new URL(str1).pathname.split("/")
.map((key, idx) => [key.replace(":", ""), idx, key.startsWith(":")])
.filter(([,,keep]) => keep);
const pathParts = pathname.split("/");
const entries = keys.map(([key, idx]) => [key, pathParts[idx]]);
return Object.fromEntries([...entries, ...searchParams]);
}
console.log(parseUrl('https://www.example.com/:version/api/:collection/:id', 'https://www.example.com/6/api/listings/3?sort=desc&limit=10'));
Above, we still need to write our own custom logic to obtain the URL parameters, however, we don't need to write any logic to extract the query string data as this is done for us by using URLSearchParams. We're also able to lower the number of .split()s used as we can obtain use the URL constructor to give us an object with a parsed URL already. If you end up using a library (such as express), you will get the above functionality out-of-the-box.

Trying to get the"name" of a javascript object supplied by an API

I am calling an API which is giving me back, among other things, an array of javascript objects. The objects in the array are named and I need to use the name in the new individual objects I am creating from the array. Problem is, I don't know how to get to the object's name.
{
"OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0},
"OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274},
}
I am after the "OldCrowMine.E9001" bit. I am sure this is quite simple, I just don't know how to search for the answer because I am not sure what to call this. I have tried searching for a solution.
Just loop - or am I missing something? Simplified raw data version.
var raw = {
"OldCrowMine.E9001":{"share":1524883404},
"OldCrowMine.S9001":{"share":1524}
};
for(var first in raw) {
console.log(first +" share -> "+ raw[first]["share"]);
}
var obj = {
"OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0},
"OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274},
}
console.log(Object.keys(obj)[0]);
Get the keys and map the name and the object:
var x= {
"OldCrowMine.E9001":{"last_share":1524883404,"score":"0.0","alive":false,"shares":0,"hashrate":0},
"OldCrowMine.S9001":{"last_share":1524,"score":"648.24","alive":true,"shares":632,"hashrate":14317274},
};
var mapped = Object.keys(x).map(function(d,i){return [d,x[d]]});
The name is map[n][0] and its object is map[n][1] where n is your item number.

Make parseFloat convert variables with commas into numbers

I'm trying to get parseFloat to convert a userInput (prompt) into a number.
For example:
var userInput = prompt("A number","5,000")
function parse_float(number) {
return parseFloat(number)
}
When userInput = 5,000, parse_Float(userInput) returns 5.
However, if the user was inputting a value to change something else (ie: make a bank deposit or withdrawl) Then I to work properly, parse.Float(userInput) needs to return 5000, not 5.
If anyone could tell me how to do this it would help me so much. Thanks in advance.
Your answer is close, but not quite right.
replace doesn't change the original string; it creates a new one. So you need to create a variable to hold the new string, and call parseFloat on that.
Here's the fixed code:
function parseFloatIgnoreCommas(number) {
var numberNoCommas = number.replace(/,/g, '');
return parseFloat(numberNoCommas);
}
I also renamed the function to parseFloatIgnoreCommas, which better describes what it does.
This is the function I use to scrub my user inputted numbers from a form. It handles anything a user may put in with a number like $ or just accidentally hitting a key.
I copied the following out of an object:
cleanInput : function(userValue){
//clean the user input and scrub out non numerals
var cleanValue = parseFloat(userValue.replace(/[^0-9\.]+/g,""));
return cleanValue;
},
To make it non-object just change the first line to cleanInput(){....
I have put together info from the comments to form a basic answer:
The answer seems to simply be to set parse_float to run :
number.replace(/,/g, "")
return parseFloat(number)
The complete code would look like this:
var userInput = prompt("A number","523,000,321,312,321")
function parse_float(number) {
number.replace(/,/g, "")
return parseFloat(number)
}
returns: 523000321312321

Accessing Images from an array?

I need to create a function where the user can access input question , and they can see different results. It's a magic eight ball simulation. I need to use an array, but i'm not sure how to do this with images.
Here's what I have now.
function eightBall() {
var answer = document.getElementById('questBox').value;
answer = answer.toLowerCase();
if (answer.search(/[?]/) > -1) {
var no = '../images/eightBallNo.png';
$('#answerImages').html(no);
}
}
I'm not sure how to do this, so any help would be appreciated. In addition, I need to make it so that when the user enters the same question, it always returns the same result. My instructions were to do this through an if statement. Again, any help would be greatly appreciated.
Create a map using an object and store each question and the resulting random mage in it. When somebody asks a question, check to see if you've already mapped that question to something. If so, use the cached result. If not, get a random image from your array, and then add it to the cache:
// empty cache to use
var answerMap = {}
// array of your images
var images = ['image_1.png', 'image_2.png', ... 'image_n.png'];
function eightBall() {
var imageToUse = false;
var answer = document.getElementById('questBox').value;
answer = answer.toLowerCase();
// this syntax could be wrong, I forget the check as my JS is rusty
// check the cache to see if we got asked this before
if (answerMap[answer] != undefined) {
// if so, use the cached image value
imageToUse = answerMap[answer];
} else {
// otherwise, get a random image, and add it to the cache
var randomIndex = Math.floor(Math.random()*images.length);
imageToUse = images[randomIndex];
answerMap[answer] = imageToUse;
}
// do whatever you need to do with the image
}
Use that URL in an IMG tag, like this:
var no = '../images/eightBallNo.png';
$('#answerImages').html('<img src='+no+'/>');
But, this doesn't use an array. Where were you needing to use an Array? An Array of image urls?

Categories