I'm trying to create a piece of JS that will parse the email address from a url query string. Once that's done, I want it to send the results to anaytics for use in whatever I need to use it in.
so basically abc.com?wemail=abc#abc.com
<script type="text/javascript">
/*Extracts email from query string using ?email=name#abc.com*/
function GetUrlValue(VarSearch) {
var SearchString = window.location.search.substring(1);
var VariableArray = SearchString.split('&');
for (var i = 0; i < VariableArray.length; i++) {
var KeyValuePair = VariableArray[i].split('=');
if (KeyValuePair[0] == VarSearch) {
return KeyValuePair[1];
}
}
The anayltics is receiving the data, but the # sign is being replaced by %40 and it isn't coding it the way I want.
I'm sure that is it simple, but what changes need to be made to ensure this works properly?
The %40 symbol you are getting is the encoded url symbol for the # symbol.
Refer to the link which refers to the usage of
decodeURIComponent() function in javascript
url decode function javascript
please check this link out
The # symbol is a originally used when the URL contains authentication info:
user:pass#myurl.com
So modern browsers will encode the # symbol in query string to %40. Use decodeURIComponent() to decode the value before sending to Segment.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURIComponent
Related
Before I go on, let me say that I've looked through a number of threads already and can't find an answer that works for me.
Basically, I've built a custom link shortener and I'm using URLSearchParams to pull the URL to be shortened and the custom slug from the URL search query as follows:
var e = window.location.search;
const urlParams = new URLSearchParams(e);
const url = urlParams.get("url");
const slug = urlParams.get("slug");
Where the format for a query is: ?url=https://google.com&slug=customslug
After the parameters are handled, the URL string is treated with trim() to remove any whitespace. The final output is encoded with encodeURIComponent() when the API I'm using (https://short.io) is called.
However, I want to be able to pass URLs with &, like so: ?url=https://google.com/&testing&slug=customslug. My ideal solution would simply treat any & that isn't part of the &slug parameter as a part of the URL contained within the &url parameter. Currently, the & character is ignored if it isn't attached to a valid parameter (url or slug).
I have tried encoding the query input using encodeURIComponent(), but that results in a failure to pick up on either defined parameter. I have also tried splitting the input using split("&slug",1), but that results in an array and I cannot pass arrays to the Short.io API.
Any suggestions?
You should use the URL Encoded ampersand symbol %26.
var e = "?url=https://google.com/%26testing&slug=customslug";
const urlParams = new URLSearchParams(e);
const url = urlParams.get("url");
const slug = urlParams.get("slug");
console.log(url);
console.log(slug);
I solved my issue by building off of #CherryDT's comment about using window.location.hash to get my URL string. Ultimately, I chose to forgo the idea of a slug in the address bar, since it would cause further problems with my script.
While this solution is only applicable for my purposes, I'm detailing the solution because it functions as a workaround for the issue of not being able to encode a passed URL string from the address bar. Might be useful to someone, someday.
var e = window.location.href.replace(window.location.hash, '');
if (e.endsWith("?") === true) {
var url = window.location.hash.substr(1);
if (url === "") {
// Error code
} else {
console.log("A URL to be shortened was provided via hash.");
// Pass url to rest of script
}
}
I am pretty poor in regex so hoping to get some help here.
I have an url which has a query string parameters. The parameter in turn is a url which has qs parameters of itself.
For eg: my url is something like
http://myurl.com/somepage?ref=/en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true
Now when i use any of the functions to extract the whole query string parameter, i somehow get only the first one.
What i am expecting is: : /en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true
But what i get is: /en-us/products-overview/find-product/home/kitchen/2980?source=google
notice that the other two parameters (isadvertisement and organic) are missing.
my function is
function getUrlParameter(name) {
var url = 'http://myurl.com/somepage?ref=/en-us/products-overview/find-product/home/kitchen/2980?source=google&isadvertisement=false&organic=true';
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(url);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
JsFiddle here:
i tried other links from SO to extract QS parameters. none of them seem to handle this scenario
The ampersands in your url are being treated as top level parameter separators. If they are part of a parameter themselves, they need to be escaped. Your escaped url would look like http://myurl.com/somepage?ref=%2Fen-us%2Fproducts-overview%2Ffind-product%2Fhome%2Fkitchen%2F2980%3Fsource%3Dgoogle%26isadvertisement%3Dfalse%26organic%3Dtrue. How you encode the url depends on where it is coming from. JS provides the encodeURIComponent() function.
Then you could use decodeURIComponent() to decode that back to the expected url. The issue is coming from having nested query parameters.
To get query parameters in general though, a built in solution using URL could be something like:
var url=new URL('...');
for (var e of url.searchParams.entries()){
console.log(e);
}
I'm building a page for digital campaigns and I'd like to personalize the content of that page based on who referred users there.
For example, A sends B a link to this page, I generate the link to be sent by A automatically on his dashboard. When B clicks the link, I want the page title to say "Hey, A referred you here"
I know the solution to this might be simple but I'm not very awesome with web dev yet. How do I
Pass this information through the link?
Collect the information on the page and put it in as part of the content?
Looking forward to suggestions for most effective implementation
Theory
You can pass information to a page through the URL using URL parameters. This method of posting data is called GET
For example, take this URL:
example.com?key1=val1&key2=val2
You can send any number of parameters using the syntax key=value (note, value is not enclosed in quotes), and separate each one with an &. You must put a question mark between the URL and the parameters.
JavaScript
You can then retrieve the URL parameters using the following JavaScript code. Insert the following at the beginning of your page.
//To get Query Strings with JS
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) {
return decodeURIComponent(s.replace(pl, " "));
},
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
To get the value of a URL parameter, do the following:
var x = urlParams.key1; // x will be "val1"
PHP
To retrieve the URL parameters using PHP, it is much simpler. You don't need to add any code to the beginning of the page as with JavaScript, as it is an inbuilt feature of PHP. Just do the following:
$x = $_GET["key1"]; // $x will be "val1"
Practice
In your case, you could make the URL show for user Albert, his unique URL for sharing could be
example.com?sender=Albert
And on your website you could put
<script>
if (urlParams.hasOwnProperty("sender")) {
document.write("Hey, " + urlParams.sender + " reffered you here!");
}
</script>
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]);
}
I have a javascript function which passes as a query string value another query string.
In other words, I want the query string to be:
http://www.somesite.com/?somequery=%3fkey%3dvalue1%2520%26%2520key2%3value3
However, if I redirect like this:
var url = 'http://www.somesite.com/?somequery=';
url += escape('?key=value1&key2=value2');
window.location = url;
it ends up as http://www.somesite.com?somequery=?key1=value1&key2=value2 in firefox and IE7 which means that I can't parse the query string correctly.
I also tried using encodeURIComponent which didn't work either.
Is there another function or a hack to force the redirect to keep the somequery value escaped??
encodeURIComponent will work. (You may or may not want the leading ‘?’, depending on what the script is expecting.)
var c= 'd e'
var query= '?a=b&c='+encodeURIComponent(c);
var uri= 'http://www.example.com/script?query='+encodeURIComponent(query);
window.location= uri;
Takes me to:
http://www.example.com/script?query=%3Fa%3Db%26c%3Dd%2520e
When you hover over that it may appear once-decoded in the browser's status bar, but you will end up in the right place.
escape/unescape() is the wrong thing for encoding query parameters, it gets Unicode characters and pluses wrong. There is almost never a case where escape() is what you really need.
Native escape method does that. but also you can create a custom encoder like:
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
this will replace keys used in query strings. further more you can apply it to any other custom encodings by adding needed key-values pairs.
function downloadFile(){
var filePath = "C:/Users/HP/Desktop/Project Folder/DemoProject/";
var fileInfo = "Error_Issue Minor Cosmetic & Major Fatal Issues (Demo_Project) (2017)_GeneratedOn_12_21_2017 21924 AM.xlsx";
if((filePath != undefined && filePath.length > 0) && (fileName != undefined && fileName.length > 0)){
var downloadUrl = "../download?fileName="+encodeURIComponent(fileName)+"&filePath="+encodeURIComponent(filePath);
$window.location = downloadUrl;
}else{
alert("Please define a fileName for downloading...");
}
}
javascript:alert(escape('?key=value1&key2=value2'));
Works fine for me?