Reputation: 2777
I'm having trouble with JS .split()
method in a GAS script. I copy and paste the headers of other google sheet as variable headers
(the usual way will be copy and paste). This pasted selection contains some empty and undefined elements. I need to turn this elements in an array. So I split it and use the .filter
to clean empty elements. But, when I run the script, the var arrayHeaders
remains equal to headers
, as if the .split(" ")
didn't make any change, this way:
This is my code:
var headers = "STUDENT Parentage GRADE YEAR DATE GUIDE";
var arrayHeaders = headers.split(" ");
// arrayHeaders = arrayHeaders.filter(function(n){return n});
Logger.log("headers = " + headers);
Logger.log("arrayHeaders = " + arrayHeaders);
Logger.log("arrayHeaders length " + arrayHeaders.length);
for (var i = 0; i < arrayHeaders.length; i++){
var NOME_Cell = sheet.getRange(1, i +1);
Logger.log("NOME_Cell" + NOME_Cell);
Logger.log("arrayHeaders[i]" + arrayHeaders[i]);
NOME_Cell.setValue(arrayHeaders[i]).setBackgroundRGB(34, 139, 34).setFontSize(font_size).setFontWeight("bold").setFontFamily("Arial");
}
If I delete all spaces after paste the string and press space again, then the .split(" ")
works well.
Before asking this question, I read this other one, but I'm still stucked with what is going wrong here.
Thanks in advance for any help!
Upvotes: 0
Views: 228
Reputation: 1867
I'm pretty sure your headers variable is not a String. Try this:
var arrayHeaders = headers.toString().split(/[\s\t]+/);
Upvotes: 1
Reputation: 5640
When you are performing split(""), make sure the words in the string are seperated by samething which are passing to .split() method. Your arrayHeaders is same as the headers.
var headers = "STUDENT Parentage GRADE YEAR DATE GUIDE";
var arrayHeaders = headers.split(" ");
// arrayHeaders = arrayHeaders.filter(function(n){return n});
Logger.log("headers = " + headers);
Logger.log("arrayHeaders = " + arrayHeaders);
Logger.log("arrayHeaders length " + arrayHeaders.length);
for (var i = 0; i < arrayHeaders.length; i++){
var NOME_Cell = sheet.getRange(1, i +1);
Logger.log("NOME_Cell" + NOME_Cell);
Logger.log("arrayHeaders[i]" + arrayHeaders[i]);
NOME_Cell.setValue(arrayHeaders[i]).setBackgroundRGB(34, 139, 34).setFontSize(font_size).setFontWeight("bold").setFontFamily("Arial");
}
Here i think, the seperation of header is not same. make sure the seperation of headers are of one space or two spaces or three spaces..
Upvotes: 0