Google Sheet custom function not returning string - string

I am new to Google Sheet scripting.
I am writing a code to strip the sixth components from a long text that is based on a naming convention. The text have 6 parts all separated by an underscore. However, my code is not returning anything
function RetailerStrip(account) {
var count = 0;
var retname = "";
var retcount = 0;
for(var i = 0, len = account.length; i < len; i++) {
if (account[i] =="_") {
++count;
}
if (count == 5) {
retname[retcount]= account[i];
++retcount;
}
}
return retname;
}
I then call this function from sheet as below
=RetailerStrip("abc_def_ghi_jkl_mno_pqr")
When I tried to declare 'retname' as an array the function did return the required text (fifth component) but the text was spread across multiple cells with on character in each cell, and not as a single string in one cell
var retname = [];
Please help

You could try this:
function RetailerStrip(str) { return str.split('_')[5]; }
The split() method creates an array.
But if you prefer to stick with the string-iteration method, you could use this:
function RetailerStrip(account) {
var count = 0;
var retname = []; // Array
var retcount = 0;
for (var i = 0, len = account.length; i < len; i++) {
if (account[i] =="_") {
++count;
}
if (count == 4) {
retname[retcount]= account[i];
++retcount;
}
}
retname.shift(); // To get rid of the underscore from the array
var retnameString = retname.join(''); // To convert the array to a string
return retnameString;
}

Related

Check only a range of checkboxes

I have this code with works brilliantly for me. I just need a small alteration to be able to select a range of cells as well, meaning:
Either H15-H17 or H22 or H26 in the attached image.enter image description here
the code I have is the following:
var CHECKBOX_CELLS = ["H15", "H22", "H26"];
function onEdit(e) {
var range = e.range;
var checkboxIndex = CHECKBOX_CELLS.indexOf(range.getA1Notation());
if (checkboxIndex > -1 && range.getValue() == true) {
var sheet = range.getSheet();
for (var i=0; i<CHECKBOX_CELLS.length; i++) {
if (i==checkboxIndex) continue;
sheet.getRange(CHECKBOX_CELLS[i]).setValue(false);
}
}
}

Hash list of cells text in Google Spreadsheet

How can I compute a MD5 or SHA1 hash of text in a list of cells? For example, I have 100 email addresses in column A row 1-100 and I wish to encrypt them all. I would like to write the encrypted emails in column B next to each decrypted email address. What is the best way to do this?
I have read the answer here, but it doesn't exactly work
I have minimal experience with google spreadsheets :-(
I began by using this script, but could only encrypt one email at a time
function MD5 (input) {
var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
var txtHash = '';
for (i = 0; i < rawHash.length; i++) {
var hashVal = rawHash[i];
if (hashVal < 0) {
hashVal += 256;
}
if (hashVal.toString(16).length == 1) {
txtHash += '0';
}
txtHash += hashVal.toString(16);
}
return txtHash;
}
Define MD5 function as you did, and then in B1 put:
=arrayformula(MD5(A1:A100))
if you add the following function underneath and then run straightToText() it works
function straightToText() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var r = 1;
var n_rows = 9999;
var n_cols = 1;
var column = 1;
var sheet = ss[0].getRange(r, column, n_rows, ncols).getValues(); // get first sheet, a1:a9999
var results = [];
for (var i = 0; i < sheet.length; i++) {
var hashmd5= GetMD5Hash(sheet[i][0]);
results.push(hashmd5);
}
var dest_col = 3;
for (var j = 0; j < results.length; j++) {
var row = j+1;
ss[0].getRange(row, dest_col).setValue(results[j]); // write output to c1:c9999 as text
}
}

Creating a attachment from Google sheet in ms Excel format via Google script

Is it possible to create an Excel format file from a Google sheet using Google script, so that it can be added as an attachment to an email?
I've got a code that takes columns with certain names (e.g. A, C, F) and turns them into a new sheet (on createCustomStatusTable() function).
https://docs.google.com/spreadsheets/d/1fZ0JMYjoIrfPIxFBVgDNU0x5X0ll201ZCU-lcaTwwcI/edit?usp=sharing
var expected = ['A','C','F'];
var newSpreadSheet = SpreadsheetApp.getActiveSheet();
var tableLastRow = newSpreadSheet.getLastRow();
var tablelastColumn = newSpreadSheet.getLastColumn();
var values = newSpreadSheet.getRange(1, 1, tableLastRow, tablelastColumn).getValues();
var rangeToCopy = [];
function in_array(value, array)
{
for(var i = 0; i < array.length; i++)
{
if(array[i] == value) return true;
}
return false;;
};
function columnsCount() {
var count = 1;
for (var i = 0; i < SpreadsheetApp.getActiveSheet().getLastColumn(); i++) {
if (in_array(values[0][i],expected))
count++;
}
return count;
};
function returnRange() {
for (var i = 1; i < SpreadsheetApp.getActiveSheet().getLastColumn()+1; i++) {
if (in_array(values[0][i-1],expected)) {
rangeToCopy.push(newSpreadSheet.getRange(1, i, newSpreadSheet.getMaxRows()));
};
};
return rangeToCopy;
};
function createCustomStatusTable() {
var targetSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Target');
for (var i = 1; i < columnsCount(); i++) {
returnRange()[i-1].copyTo(targetSheet.getRange(1,i));
};
};
Thank you in advance for any help
You can create an EXCEL type file with DriveApp:
The problem is, that the content must be a string. And I haven't tested for a way to make that work.
I know this doesn't answer your question. Hopefully someone knows for sure how to create an EXCEL file from a Google Sheet.

AS3 String splitting keeping tags

I have variable strings that can contain tags, e.g.:
"<b>Water</b>=H<sub>2</sub>O"
What i want is an array that should look like:
Array[0] <b>Water</b>
Array[1] =H
Array[2] <sub>2</sub>
Array[3] O
How can i do this?
Thanks!
Give this a go, it uses a common regex to find html tags to get it separated and then indexOf and substring to assemble it back together.
function splitWithTags(str:String):Array {
var tags:Array = str.match(/(<(.|\n)*?>)/g);
var c:int = tags.length;
if(c%2 != 0) c--; // if it's odd, decrement to make even so loop works, last tag will be ignored.
if(c<2) return [str]; // not enough tags so return full string
var out:Array = [];
var end:int = 0;
var pos1:int, pos2:int;
for(var i:int = 0; i<c; i+=2) {
// find position of 2 tags.
pos1 = str.indexOf(tags[i]);
pos2 = str.indexOf(tags[i+1]);
if(pos1 >= end+1) { // there's some stuff not between tags to add
out.push(str.substring(end, pos1));
}
end = pos2+tags[i+1].length
out.push(str.substring(pos1, end));
}
if(end < str.length) { // there is substr at end
out.push(str.substring(end, str.length));
}
return out;
}

Union function - Passing argument in custom function - Google-spreadsheet

While trying to answer
this question, I found a strange behavior.
Here's my code :
function remove(val, array){
var res = new Array();
for(var i=0; i<array.length; i++){
if(array[i] != val){
res.push(array[i]);
}
}
return res;
}
//we assume that there is no duplicates values inside array1 and array2
function my_union(array1, array2){
var longuer;
var shorter;
var arrayRes = new Array();
if(array1.length < array2.length){
longuer = array2;
shorter = array1;
} else {
longuer = array1;
shorter = array2;
}
for(var i=0; i<longuer.length; i++){
arrayRes.push(longuer[i]);
shorter = remove(longuer[i], shorter);
}
for(var i=0; i<shorter.length; i++){
arrayRes.push(shorter[i]);
}
return arrayRes;
}
function test(){
Browser.msgBox(my_union([1,2,3], [1,2]));
}
The message box clearly says 1,2,3 but when you try to invoke this function inside a spreadsheet with the same values, it fails to delete duplicated values, why ?
**EDIT : **
Thanks to Henrique's answer , here's the code :
function remove(val, array){
var res = new Array();
for(var i=0; i<array.length; i++){
if(array[i] != val){
res.push(array[i]);
}
}
return res;
}
function matFlattener(matrix){
var array = new Array();
for(var i=0; i<matrix.length; i++){
for(var j=0; j<matrix[i].length; j++){
array.push(matrix[i][j]);
}
}
return array;
}
function my_union(matrix1, matrix2){
//assert no duplicate values in matrix1 and matrix2
var longuer;
var shorter;
var array1 = matFlattener(matrix1);
var array2 = matFlattener(matrix2);
var arrayRes = new Array();
if(array1.length < array2.length){
longuer = array2;
shorter = array1;
} else {
longuer = array1;
shorter = array2;
}
for(var i=0; i<longuer.length; i++){
arrayRes.push([longuer[i]]);
shorter = remove(longuer[i], shorter);
}
for(var i=0; i<shorter.length; i++){
arrayRes.push([shorter[i]]);
}
return arrayRes;
}
When you call the custom function from the spreadsheet and pass a multi-range parameter, this parameter will always be a matrix, regardless if you pass a single row or column.
To test the behavior like the spreadsheet does, you should change your test function like this:
function test() {
//note the "extra" brackets
Browser.msgBox(my_union([[1,2,3]],[[1,2]]); //passing "single" rows
Browser.msgBox(my_union([[1],[2],[3]],[[1],[2]]); //passing "single" columns
}
The solution is adjust your my_union formula to account for it.

Resources