I wanted to create a custom website where some parameters will be fetched from URL and displayed inside html.
Let the link be: https://www.example.com?abc=anything&def=hello world&ghi=father & son
The values are fetched from an excel sheet, so I cannot edit the spaces, etc.
I used jQuery for the same.
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
var abc = GetURLParameter('abc');
The && is due to the fact that some of my parameter may contain & like A & B Product
And I also have the problem that, the link will be created like above with spaces, so need to parse that back to normal text as well.
And to display the same, I am using:
<p>document.write(abc)</p>
I want to fetch data in URL somehow which will work with Github Hosting and display it in HTML without any HTML Special Character Problem. Github don't support PHP, else this was a piece of cake.
Any help is appreciated.
To make variables URL safe you can encode them using encodeURI(). For example:
let a = 'A & B Product';
console.log(encodeURI(a));
// will output: `A%20&%20B%20Product`
And then to decode on the other side:
console.log(decodeURI(a));
// will output `A & B Product`
Related
I'm currently using the following JavaScript in a Google Chrome Extension to automate the 'add to cart' process for purchasing sneakers on nike.com;
var size_i_want = "11";
function fRun()
{enter code here
// Select size option.
var sizesList=document.getElementsByName("skuAndSize")[0];
for(var i=0; i<sizesList.length; i++)
{
if(sizesList.options[i].text.trim() == size_i_want)
{
sizesList.selectedIndex = i;
}
}
var aButtons = document.getElementsByTagName("button");
for(var i = 0; i < aButtons.length; ++i)
{
if(aButtons[i].className.indexOf("add-to-cart") > -1)
{
aButtons[i].click();
}
}
}
function fTick()
{
if(document.getElementsByName("skuAndSize")[0] != undefined)
{
setTimeout("fRun()", 600);
//fRun();
}else{
setTimeout("fTick()", 300);
}
}
setTimeout("fTick()", 300);
This script works perfectly for nike.com in the States, however does not work correctly for nike websites in other countries like the UK and Sweden.
As you can probably tell I am new to JavaScript and am still researching high and low to understand the language. However I understand this comes down to the fact that
var size_i_want = "11";
value is set as an integer (number) however on the Nike UK website the node that this affects contains letters, for example "UK 10.5".
Would somebody be able to help me declare a new variable and set it's value so that it contains both letters and numbers? I also have a feeling that this will impact the script as well, so help around that area is much appreciated too.
In javascript, variables are not typesafe, so you don't declare them as integers or strings. Coincidently:
var size_i_want = "11";
This is already a string. So you should already be able to add letters to it. Just change it to:
var size_i_want = "UK 10.5";
As millerbr already said javascript is not type safe.
The mix of letters and numbers should not have impact on the script, because
size_i_want = "11";
size_i_want = "UK 10.5";
are both strings.
i am new to Google apps script, i want to create string of random characters in the code given below in variable body2.
function myfunction() {
var files = DriveApp.getFiles();
while (files.hasNext(`enter code here`)) {
Logger.log(files.next().getName());
}
var recipient = Session.getActiveUser().getEmail();
var subject = 'A list of files in your Google Drive';
var body1 = Logger.getLog();
var body2;
for(var i=0;i<6;i++)
{
body2[i]=BigNumber.tostring("Math.floor(Math.random()*11)");
}
body=body1+body2;
MailApp.sendEmail(recipient, subject, body);
};
but when i run this function, it says "TypeError: Cannot find function tostring in object 0. (line 12, file "Code") " i can't understand how to solve this error?
Why we have to multiply random by 11 , can it be multiplied with any integer number?
what if i want that string in only capital letters.!
Some other question
1) i don't have enough knowledge of JavaScript, is it good to learn GAS directly?
2) i can't find proper written material or documentation for GAS , the material available at Google's official site is seems to be updating time by time , what to do then ? any link to material would help me .!
I guess I just figured
function randomStr(m) {
var m = m || 15; s = '', r = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i=0; i < m; i++) { s += r.charAt(Math.floor(Math.random()*r.length)); }
return s;
};
Hope someone finds it helpful.
As for a random string use this its better:
Math.random().toString(36). 36 is the base thus will use letters and numbers in the string.
As for gas documentation, the official page is pretty complete. It changes because it constantly improves and adds new services.
I have this charIdGeneration() in my GAS library
function charIdGenerator()
{
var charId ="";
for (var i = 1; i < 10 ; i++)
{
charId += String.fromCharCode(97 + Math.random()*10);
}
//Logger.log(charId)
return charId;
}
I am trying to parse a CSV file I made in Excel. I want to use it to update my Google map. This Google map is in a mobile app that I am developing with Eclipse for Android.
Honestly, I am not sure how to write the JavaScript. Any help will be greatly appreciated. I would be happy to credit your work.
I just want some JavaScript to run when the user hits a button that does the following:
Locates users current location (I have already done this part!)
Locate nearby locations as entered in the .CSV excel file by parsing the .CSV
Display a small link inside every locations notification bubble that says "Navigate" that when the user clicks it, opens google maps app and starts navigating the user to that location from the users current location (Geolocation).
This is the ONLY part I need to finish this application. So once again, any help at all will be greatly appreciated. Thanks everyone!
Honestly, I've been round and round with this problem. The CSV format is not made for easy parsing and even with complicated RegEx it is difficult to parse.
Honestly, the best thing to do is import it into an FormSite or PHPMyAdmin, then re-export the document with a custom separator that is easier to parse than ",". I often use "%%" as the field delimiter and everything works like a charm.
Dont know if this will help but see http://www.randomactsofsentience.com/2012/04/csv-handling-in-javascript.html if it helps...
Additional:
On top of the solution linked to above (my preference) I also used a shed load of stacked regular expressions to token a CSV but it's not as easy to modify for custom error states...
Looks heavy but still only takes milliseconds:
function csvSplit(csv){
csv = csv.replace(/\r\n/g,'\n')
var rows = csv.split("\n");
for (var i=0; i<rows.length; i++){
var row = rows[i];
rows[i] = new Array();
row = row.replace(/&/g, "&");
row = row.replace(/\\\\/g, "\");
row = row.replace(/\\"/g, """);
row = row.replace(/\\'/g, "'");
row = row.replace(/\\,/g, ",");
row = row.replace(/#/g, "#");
row = row.replace(/\?/g, "?");
row = row.replace(/"([^"]*)"/g, "#$1\?");
while (row.match(/#([^\?]*),([^\?]*)\?/)){
row = row.replace(/#([^\?]*),([^\?]*)\?/g, "#$1,$2?");
}
row = row.replace(/[\?#]/g, "");
row = row.replace(/\'([^\']*)\'/g, "#$1\?");
while (row.match(/#([^\?]*),([^\?]*)\?/)){
row = row.replace(/#([^\?]*),([^\?]*)\?/g, "#$1,$2?");
}
row = row.replace(/[\?#]/g, "");
row = row.split(",")
for (var j=0; j<row.length; j++){
col = row[j];
col = col.replace(/?/g, "\?");
col = col.replace(/#/g, "#");
col = col.replace(/,/g, ",");
col = col.replace(/'/g, '\'');
col = col.replace(/"/g, '\"');
col = col.replace(/\/g, '\\');
col = col.replace(/&/g, "&");
row[j]=col;
}
rows[i] = row;
}
return rows;
}
I had this problem which is why I had to come up with this answer, I found on npm a something called masala parser which is indeed a parser combinator. However it didn't run on browsers yet, which is why I am using this fork, the code remains unchanged. Please read it's documentation to understand the Parser-side of the code.
import ('https://cdn.statically.io/gh/kreijstal-contributions/masala-parser/Kreijstal-patch-1/src/lib/index.js').then(({
C,
N,
F,
Streams
}) => {
var CSV = (delimeter, eol) => {
//parses anything beween a string converts "" into "
var innerstring = F.try(C.string('""').returns("\"")).or(C.notChar("\"")).rep().map(a => a.value.join(''));
//allow a string or any token except line delimeter or tabulator delimeter
var attempth = F.try(C.char('"').drop().then(innerstring).then(C.char('"').drop())).or(C.charNotIn(eol[0] + delimeter))
//this is merely just a CSV header entry or the last value of a CSV line (newlines not allowed)
var wordh = attempth.optrep().map(a => (a.value.join('')));
//This parses the whole header
var header = wordh.then(C.char(delimeter).drop().then(wordh).optrep()).map(x => {
x.header = x.value;
return x
})
//allow a string or any token except a tabulator delimeter, the reason why we allow newlines is because we already know how many columns there is, so if there is a newline, it is part of the value.
var attempt = F.try(C.char('"').drop().then(innerstring.opt().map(a=>(a.value.__MASALA_EMPTY__?{value:""}:a))).then(C.char('"').drop())).or(C.notChar(delimeter))
//this is merely just a CSV entry
var word = attempt.optrep().map(a => (a.value[0]?.value??a.value[0]));
//This parses a CSV "line" it will skip newlines if they're enclosed with doublequotation marks
var line = i => C.string(eol).drop().then(word.then(C.char(delimeter).drop().then(word).occurrence(i - 1).then(C.char(delimeter).drop().then(wordh)))).map(a => a.value);
return header.flatMap(a => line(a.header.length - 1).rep().map(b => {
b.header = a.header;
return b
}))
};
var m = {
'tab': '\t',
"comma": ",",
"space": " ",
"semicolon": ";"
}
document.getElementById('button').addEventListener('click', function() {
var val = document.getElementById('csv').value;
var parsedCSV = CSV(m[document.getElementById('delimeter').value], '\n').parse(Streams.ofString(val)).value;
console.log(parsedCSV);
})
})
Type some csv<br>
<textarea id="csv"></textarea>
<label for="delimeter">Choose a delimeter:</label>
<select name="delimeter" id="delimeter">
<option value="comma">,</option>
<option value="tab">\t</option>
<option value="space"> </option>
<option value="semicolon">;</option>
</select>
<button id="button">parse</button>
I would suggest stripping the newlines and the end of the file. Because it might get confused.
This appears to work. You may want to translate the Japanese, but it is very straight-forward to use:
http://code.google.com/p/csvdatajs/
I've written a PHP-script that parses a list from remote website and output the result as JSON form my iPhone app which is built on Titanium Mobile.
This is my header: header('content-type:application/json;charset=utf-8');
Also tried with ISO-8859-1 but problem persists.
I print the textResponse in the titanium console and see that the &-characters are represented as &. Same result when I make the same request in my web browser.
I try to replace & with & using replace('&', '&') but it has no effect, & is still &.
var events = JSON.parse(this.responseText);
Titanium.API.info(events);
for (var i = 0; i < events.length; i++) {
var id = events[i].id;
var title = events[i].title;
var amp = title.search('&');
if (amp != -1) {
title.replace('&', '&');
Titanium.API.info(amp);
Titanium.API.info(title);
}
var row = Titanium.UI.createTableViewRow({title: title, id: id, hasChild: true});
rowData[i] = row;
}
title = title.replace('&', '&');
You should post your php script as reference. You may want to make sure you are decoding the URLs prior to printing them to the JSON.
I see a decent amount of traffic, around 100 visits a day, that comes from an images.google domain but shows as referral traffic rather than organic in Google Analytics. I have some custom code to pull keywords out and set an organic source for a few variations of what Google Image Search referrers look like, and it works for every referrer I can run it against from the server log.
var ref = document.referrer;
if (ref.search(/www.google/) != -1 && ref.search(/imgres/) != -1) {
var regex = new RegExp("www.google.([^\/]+).*");
var match = regex.exec(ref);
ref = 'http://images.google.' + match[1] + '?' + ref.split('?')[1];
_gaq.push(['_setReferrerOverride', ref]);
} else if (ref.search(/maps.google/) != -1 && ref.search(/q=/) == -1) {
var regex = new RegExp("maps.google.([^\/]+).*");
var match = regex.exec(ref);
ref = 'http://maps.google.' + match[1] + '?q=' + encodeURIComponent('(not provided)');
_gaq.push(['_setReferrerOverride', ref]);
}
function splitUrl(url) {
var vals = {};
var split = url.split('?');
vals.base = split[0];
if(split.length > 1) {
var vars = split[1].split('&');
vals.params = {};
for(var i = 0, len = vars.length; i < len; i++) {
var valSplit = vars[i].split('=', 2);
vals.params[valSplit[0]] = valSplit[1];
}
}
return vals;
}
function joinUrl(urlObj) {
var vars = [];
for(key in urlObj.params)
if(urlObj.params.hasOwnProperty(key))
vars.push(key + '=' + urlObj.params[key]);
return urlObj.base + '?' + vars.join('&');
}
//fix keyword for old google image search
if(ref.match(/^http:\/\/images\.google\./) || ref.match(/^http:\/\/images\.google$/)) {
var refUrl = splitUrl(ref);
if(refUrl.params.prev && !refUrl.params.q) {
var prev = decodeURIComponent(refUrl.params.prev);
if(prev.indexOf('?q=') !== -1 || prev.indexOf('&q=') !== -1) {
var prevUrl = splitUrl(prev);
refUrl.params.q = prevUrl.params.q;
if(!refUrl.params.q)
refUrl.params.q = encodeURIComponent('(not provided)');
delete prevUrl.params.q;
refUrl.params.prev = encodeURIComponent(joinUrl(prevUrl));
}
_gaq.push(['_setReferrerOverride', joinUrl(refUrl)]);
} else if(!refUrl.params.q) {
refUrl.params.q = encodeURIComponent('(not provided)');
_gaq.push(['_setReferrerOverride', joinUrl(refUrl)]);
}
}
_gaq.push(['_addOrganic', 'images.google', 'q']);
_gaq.push(['_addOrganic', 'maps.google', 'q', true]);
This handles all of the referres that look like:
http://images.google.com/?q=
and
http://www.google.com/?imgres=
I don't know where the referral traffic is coming from. Has anyone else seen this?
Well it is natural for Google to recognize this domain as a referral as GA only includes by default a certain number of domains as Search Engines.
To solve this problem you can include such domain as a Search Engine using the "addOrganic()" Method.
To use this method, you must specify not only the domain of the search engine, but also the query string parameter used for searches. In the case of images.google.com it's "q".
On your GA tracking code, add the line:
_gaq.push(['_addOrganic', 'images.google.com', 'q', true]);
You can get more info on the Ga Help Site.
Hope this info helps,
Augusto Roselli
Web Analytics - digitalcube
#_digitalcube
www.dp6.com.br
If someone clicks on an image that shows up on standard google search, not images.google, the url might be different. You should try some urls from there. But besides that, the google images links that popup on normal Google will not include the query string if the user is logged in into a Google Account. It happened on Oct 2011 here are a couple of links on the subject:
Official Google Statement
Avinash's, always worth reading, opinion.
On normal organic google links Google Analytics shows these visits as coming from a (not provided) keyword from an organic medium. But if you click on an image on the SERP it won't be identified as an organic medium. It will be identified as a Referral, and that's probably the ones you are seeing.
So what you need to do is to verify if the google images link has the q parameter or not. If it doesn't have than it's coming from a logged user and should be reported as (not provided) to be consistent with google organic keywords. Just append &q=(not provided) to the _setReferrerOverride url you got. Remember to url encode that before appending to the url.
I'm also posting here the code I use. It's from Google Forums. But it's very similar to yours and doesn't handle the (not provided) keywords issue yet.
Note that it's very similar to yours with a few notable differences.
You strip the whole path from the images url, while mine keeps the
path.
You don't use the "true" keyword on "_addOrganic", that
may cause Google Images to be reported as google instead of
images.google source on your reports.
Here's the code I currently use:
//handle google images referrer
var ref = document.referrer;
if ((ref.search(/google.*imgres/) != -1)) {
var regex = new RegExp("\.google\.([^\/]+)(.*)");
var match = regex.exec(ref);
_gaq.push(
['_setReferrerOverride', 'http://images.google.' + match[1] +
unescape(match[2])],
['_addOrganic', 'images.google', 'q', true]
);
}
I'll be updating my code to handle (not provided) google images links and will post here as soon as I have it.