Utilities.formatString() New Apps Script method, not working as intended - javascript

I am using the new method: Utilities.formatString()
In the Google Documentation is says it is similar to sprintf %-style.
I searched and read this article about sprintf in PHP.
I cannot seem to get this to work as intended. It is meant to pad this 8 character string with 4 leading zeros. I know there are other ways to do this, But I am trying to get a handle on this sprintf / formatString thing.
var noFormat = "12345678";
var formatted = Utilities.formatString("%012s", noFormat);
I expected the var formatted to be equal to "000012345678".
my debugger tell me that formatted = 0, or sometimes it throws an error..
I am confused.

try it like this :
function xxx(){
var noFormat = '12345678'
var formatted = Utilities.formatString("%012d", noFormat);
Logger.log(formatted)
}
the different parameters that can be used are easy to find on the web, here is an example that explains how the argument must be evaluated in php but the usage is the same.
Logger result :

Related

Is there any way of getting the GET parameters with pure Javascript?

Let's say I have a page called https://randompagename.com, I know I can send GET parameters to this page using this syntax: https://randompagename.com/?parameter1="one"&parameter2="two".
I also know that on a Node.js web app I have an easy way of getting these parameters inside a variable. However, when I'm using pure frontend Javascript without Node.js, I usually solve this problem with something like:
const myURL = decodeURI(window.location.href)
This way, I discover that my page is https://randompagename.com/?parameter1="one"&parameter2="two" and then I can parse it excluding everything after the first = sign and then splitting everything on &. Well, even though this is functional I'm probably missing an easier way of solving this problem. How can I get GET parameters on a page without using any library?
You can use the URL object https://developer.mozilla.org/en-US/docs/Web/API/URL
If the URL of your page is https://example.com/?name=Jonathan%20Smith&age=18 you could parse out the name and age parameters using:
let searchString = (new URL(document.location)).search; //?name=Jonathan%20Smith&age=18
let params = (new URL(document.location)).searchParams;
let name = params.get('name'); // is the string "Jonathan Smith".
let age = parseInt(params.get('age')); // is the number 18

Google App Script new editor - string property double underlined

Probably a nube question but I have a line of code:
var c = message.substring(i, i + 1);
It works but in the new Google App Script editor, the string property "substring" has a double-underline under it, which seems to suggest that it's wrong, but it actually works!
"Show Fixes" gives me only two options - to ignore the "error" or disable checking, neither of which seems like what I want to do. Any ideas?
I think it is due to how the variable "message" is defined. I did a quick test trying to replicate your scenario and this is what I got:
With warning:
var message = 0
message = '123456789'
var c = message.substr(1, 5);
Without warning:
var message = '0'
message = '123456789'
var c = message.substr(1, 5);
Both cases have the same result without errors. If you provide more code I can check why the warning is appearing.
edit:
As you have said in the comments, your variable is being defined from the range of a SpreadSheet using getValue(), this method returns an object with the value of the cell. If you want to obtain a string you should use getDisplayValue(). You can also use the built-in method toString() to make sure that any variable is converted into a string.
References:
getValue()
getDisplayValue()

Javascript regex match doesn't run correctly

okay I give up. Here's my code:
var re = /href="(http.*\.jpg)"/g;
var mp3s = body.match(re);
it finds pictures, but it returns href="http://www.picture.com/smthg.jpg"
instead of returning http://www.picture.com/smthg.jpg
any idea why?
The result from match() is actually an object.
I think you need to access the first element on that object.
For example:
body.match(re)[1]
This is where the actual result is kept.
Shameless self-promotion:
I've written a small guide for me, I can never remember how to use these either. It's here: http://queirozf.com/reminders/javascript-regular-expressions-usage-reminder
try
var re = /(http.*\.jpg)/g;
var mp3s = body.match(re);
since you don't need the href.
You want to match the regular expression, but then return just the portion in brackets.
To do this, call the regular expressions exec method. For example:
var body = 'stuff stuff morestuff href="http://www.picture.com/smthg.jpg" and some more stuff';
var re = /href="(http.*\.jpg)"/g;
var regexResults = re.exec(body);
var mp3s = regexResults[1];
alert(mp3s);
Having given you this answer, I must implore you to find a different way to solve this problem. You cannot parse HTML using regular expressions. No matter how sophisticated your regular expression gets, there will be a legal HTML example which will break it.

This code doesn't work in IE

Hi so I have this jQuery/JS script. That basically takes an encoded URL string and parses it and saves variable values into variables.
Basically what PHP's $_GET does.
function getUrlVars()
{
var map = {};
var parts = window.location.search.replace(/[?&]+([^=&]+)(=[^&]*)?/gi,
function(m,key,value)
{ map[key] = (value === undefined) ? true : value.substring(1); });
return map;
}
Basically this script does what I want. From this URL string:
/autopop.html?Email=test%40test.com&LastName=Test+last&&FirstName=+Test+First
I get the values:
Email = test%40test.com
LastName = Test+last
FirstName = +Test+First
What I want to do is Auto-populate a form on this same page with this information.
(I know what you're thinking a server-side script would be a better solution but the boss says we don't have access to that, trust me, I've tried)
Long story short, here's the rest of my code:
var keys = getUrlVars();
$(document).ready(function(){
var fname = keys['FirstName'].replace(/\+/g , " ").trim();
var lname = keys['LastName'].replace(/\+/g , " ").trim();
var email = decodeURIComponent(keys['Contact0Email'].replace(/\+/g , " ")).trim();
$("#Email").val(email);
$("#FirstName").val(fname);
$("#LastName").val(lname);
});
This code gets the job done. All except for one browser. IE.
IE doesn't support decodeURIComponent or so I've read. In any case, I tried using other functions like decodeURI and escape all producing unwanted results.
My google searches have yielded nothing but, semi-interesting articles (totally off-topic but thought I'd just share that).
No solutions. Can anyone shed some light? How do I make this work on IE?
You have read wrong, decodeURIComponent works just fine in IE, even in IE6.
However, trim doesn't work in IE browsers prior to IE 9 and that's what causing your script to crash.
For working alternative, see the accepted answer here: .trim() in JavaScript not working in IE
Or use the jQuery trim() method as you're already using jQuery anyway.

What JavaScript library should I use for parsing URL parameters?

How do I parse URL parameters in JavaScript? (These are the parameters I would ordinarily call GET parameters or CGI parameters, but in this case the page is basically submitting to itself, not a server, so there is no GET request and definitely no CGI program.)
I've seen a number of routines on the net that I can copy, but I have no idea how robust any of them are. I'm used to other languages like Perl and Java where I can rely on an extremely well-tested and robust library that I know will handle millions of little edge-cases in the standard. I would like the same here, rather than just cutting and pasting an example.
jQuery URL Utils or jQuery URL Parser.
Here's are two simple functions that do the job : http://adamv.com/dev/javascript/querystring
Here is a sample of the API Reference :
var qs = new Querystring();
// Parse a given querystring
var qs2 = new Querystring("name1=value1&name2=value2");
var v1 = qs2.get("name1");
var v3 = qs2.get("name3", "default value");
If it's "submitting to itself," do you need to do GET parameters?
But if you do, most browsers now have the decodeURIComponent function which will handle individual parameters; your job is to split them on & (String#split will do that nicely). If you want a library, jQuery and Prototype are both well-used and tested.
The best way I have found is to simply do it yourself and funnel the params into a global key/value object.
Getting quer params is simple...
just take a couple of .split()'s
var myquery = thewholeurl.split("?")[1]; //will get the whole querystring with the ?
then you can do a
myparams = myquery.split("&")
then you can do
for each param in myparams
{
temp = param.split("=");
mykeys.push(temp[0]);
myvalues.push(temp[1]);
OR
myObject[temp[0]] = temp[1];
}
It's just a matter of style.
This is not perfect code, just psuedo stuff to give you the idea.
I use the parseUri library available here:
http://stevenlevithan.com/demo/parseuri/js/
It allows you to do exactly what you are asking for:
var uri = 'http://google.com/?q=stackoverflow';
var q = uri.queryKey['q'];
// q = 'stackoverflow'
I've been using it for a while so far and haven't had any problems.
I found this useful for simple url parsing, modifying url (like adding new query params): https://github.com/derek-watson/jsUri
I think this library would work quite well, it is independent so you can use it with JQuery or with YAHOO or Dojo, another advantage is that it is pretty well documented.
http://www.openjsan.org/doc/t/th/theory/HTTP/Query/0.03/lib/HTTP/Query.html
You can use HTTP.Query to do all of the work for you in this case. It is only like 1.2 KB compressed so you could even include it in a bigger library if you wanted.
I recommend query-string library
Installing:
npm install query-string
Usage:
import queryString from 'query-string';
console.log(location.search);
//=> '?foo=bar'
const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}
parsed.foo = 'unicorn';
parsed.ilike = 'pizza';
const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza'
location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'
https://www.npmjs.com/package/query-string
Javascript has no built in support for URL parameters.
Anyway, the location.search property returns the portion of current page URL starting from the question mark ('?').
From this, you can write your own parameter parser or you can make use of one of those available in most common Javascript frameworks, such as JQuery and similar.

Categories