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 .filterto 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!
I'm pretty sure your headers variable is not a String. Try this:
var arrayHeaders = headers.toString().split(/[\s\t]+/);
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..
Related
My goal is to edit the string (which has an email) to mask the first part, like say the email is johndoe#abc.com then I should output j*****e#abc.com.
var maskPII = function(S) {
var ans = "";
if(S.includes("#")){
S = S.toLowerCase();
var parts = S.split("#");
var first = parts[0];
for(var i=0;i<parts[0].length;i++){
if(i!=0 && i!=parts[0].length - 1)
first[i] = '*';
}
ans = first +"#" +parts[1];
}else{
}
return ans;
};
However in my loop I can't change the characters to asterisks.
After execution I see value of first still same as parts[0] and has no asterisks, can some one explain why? Also, what would I need to do to modify the variable inside loop?
To answer your question... javascript allows you access values of a string using [] indexing.. but that is read only access... you cannot insert/replace values using that operator.
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
When using bracket notation for character access,
attempting to delete or assign a value to these properties will not succeed.
The properties involved are neither writable nor configurable.
(See Object.defineProperty() for more information.)
You need to extract the values you want to keep from the existing string and build up a new string as noted in other answers...
Well, this's what you're looking for, and this will be the output j*****e#abc.com.
var ans = "";
var S = "johndoe#abc.com"; //example
S = S.toLowerCase();
var parts = S.split("#");
var first = "";
for(var i = 0; i < parts[0].length; i++){
if(i != 0 && i != parts[0].length - 1){
first += '*';
}else{
first += parts[0][i];
}
}
ans = first +"#"+ parts[1];
console.log(ans);
Here is the code with your approach:
var maskPII = function(S) {
var ans = "";
if(S.includes("#")){
S = S.toLowerCase();
var parts = S.split("#");
var first = parts[0][0];
for(var i=0;i<parts[0].length;i++){
if(i!=0 && i!=parts[0].length - 1)
first += '*';
}
ans = first + parts[0][parts[0].length - 1] +"#" +parts[1];
}else{
}
return ans;
};
But if i were you i would use:
var mail = "johndoe#abc.com";
mail = mail.replace(/(?<=.)(.+?)(?=.#)/gi, '*'.repeat(mail.split('#')[0].length - 2));
console.log(mail);
You can use the bracket notation on a string (like an array) to get the character at a specific index, but you can't use this to change characters. So first[i] = '*' in your code wont do anything.
Strings in JavaScript are immutable. This means that if you want to change a string, a new string instance will be created. This also means that when you change a string in a for-loop, it can impact performance. (Although in this case the difference wont be noticeable.
)
I would use this code:
function maskPII(str) {
const indexOfAt = str.indexOf('#');
if (indexOfAt <= 2) {
return str;
}
return str[0] + '*'.repeat(indexOfAt - 2) + str.substring(indexOfAt - 1);
}
const email = 'johndoe#abc.com';
console.log(email);
console.log(maskPII(email));
It will look for the index of the # sign. If the index is less or equal than 2, (when not found the index will be -1) it will return the original string.
Otherwise it will get the first character, calculate the amount of asterisks needed (index of the # sign -2) and repeat those and then add the rest of the original string.
I have column in my database named rate but the datatype is string and has values like '2000+'. When I try to show this value using jQuery, why is it only showing 2000 without the '+' sign?
for (var j = 0; j < dtt2.length; j++) { if (dt0[i].CategoryID === dtt2[j].CategoryID) { var rate = dtt2[j].Rate; alert(rate.tostring()); $("#" + tbl).append('<tr><td>' + dtt2[j].ServiceName + '</td><td width="20%">₹ ' + rate.tostring() + '</td></tr>'); } }
this code is working when running on local host but when i am hosting on production the error comes string without + sign
Below is the code behind code-
foreach (DataRow dr in dt2.Rows)
{
ServiceRateList sd = new ServiceRateList();
sd.ServiceDetailID = Convert.ToInt32(dr["ServiceDetailID"]);
sd.ServiceName = dr["ServiceName"].ToString();
sd.CategoryID = Convert.ToInt32(dr["CategoryID"].ToString());
sd.CategoryName = dr["CategoryName"].ToString();
sd.Rate = dr["rate"].ToString();
bislist.Add(sd);
}
Note sure how you displaing plus sign in your JS codes.
But here work-around is to escape the plus sign by preceding it with a backslash.
var data = dbrawdata.replace('+', '\\+');
It would be good to answer your question add some line of your codes.
As i understood
Very simple,
var value='2000+';
value.toString(); // => '2000+'
OR
String('2000+'); // '2000+'
I have a script that will insert the checked checboxes and radios in the value() of an input tag.
var burgernavn = meat + " with " + bread + " and " + onion + tomato + cheese + salad;
$('#burger-navn').val(burgernavn);
Onion, tomato, cheese and salad needs to have1 " ," between them, except the last two who need " and " between them.
Thats the first thing.
Second thing is that these variables represent checkboxes, so they can be undefined, in which case they should not be put into $('#burger-navn').val(). They can all be undefined, in which case no commas or "and" should be put in.
I hope this is accomplishable.
Capture all checked values in an array (this makes sure that whatever values in this array, all are defined). Also, it will give you count of values that you need to pass to input box.
var checkedValues = document.getElementsByClassName('checkbox');
Iterate over this array, check for last values. (Check my comments in below code snippet)
var commaValues = "", otherValues= "";
//we are iterating only until (total values -2)
for(var i = 0; i < checkedValues.length - 2 ; i++){
//append comma with each value
commaValues += checkedValues[i].concat(",");
}
//append 'And' for last two values if total valuesa re more than one
if(checkedValues.length > 1){
otherValues = checkedValues[checkedValues.length-1].concat("and", checkedValues[checkedValues.length])
}
else if(checkedValues.length == 1){
otherValues = checkedValues[0];
}
//finally concat both strings and put this concated string in input
$('#burger-navn').val(otherValues.concat(commaValues));
So, I hope you got the idea. This code snippet might need a bit tweak since I didn't had your html code and sample data, but it is easily doable using this snippet as reference. Cheers
You can do this pretty easy with jQuery $.map.
var checkboxes = $('input:checkbox');
var commaString = $.map($('input:checkbox'), function( ele, i ) {
return $(ele).val() + (i + 2 == checkboxes.length ? " and" : (i + 1 != checkboxes.length) ? ",": "");
}).join(" ");
This is the script that i am using to fetch a particular cookie lastvisit :
AFTER THE EDIT
// This document writes a cookie
// called from index.php
window.onload = makeLastVisitCookie;
function makeLastVisitCookie() {
var now = new Date();
var last = new Date();
now.setFullYear(2020);
// set the cookie
document.cookie = "lastvisit=" + last.toDateString() + ";path=/;expires=" + now.toGMTString();
var allCookies = document.cookie.split(";");
for( var i=0 ; i < allCookies.length ; i++ ) {
if(allCookies[i].split("=")[0]== "lastvisit") {
document.getElementById("last_visit").innerHTML = "You visited this site on" + allCookies[i].split("=")[1];
} else {
alert("testing..testing..");
}
}
}
From this script the if part never works though there are 5 cookies stored from my website. (including the cookie that i am saving from this script) What is the mistake that i am making while fetching the cookie named lastvisit ?
You're splitting the cookie by ; an comparing those tokens with lastvisit. You need to split such a token by = first. allCookies[i] looks like key=val and will never equal lastvisit. Een if allCookies[i] == "lastvisit" is true, the result will still not be as expected since you're showing the value of allCookies[i + 1] which would be this=the_cookie_after_lastvisit.
if(allCookies[i].split("=") == "lastvisit") { should be:
var pair = allCookies[i].split("=", 2);
if (pair[0].replace(/^ +/, "") == "lastvisit") {
"You visited this site on" + allCookies[i+1]; should be:
"You visited this site on" + pair[1];
The 2 argument of split makes cookies like sum=1+1=2 be read correctly. When splitting cookies by ;, the key may contain a leading space which much be removed before comparing. (/^ +/ is a regular expression where ^ matches the beginning of a string and + one or more spaces.)
Alternatively, compare it directly against a RE for matching the optional spaces as well (* matches zero or more occurences of a space character, $ matches the end of a string):
if (/^ *lastvisit$/.test(pair[0])) {
I've tested several ways to get a cookie including using regular expressions and the below was the most correct one with best performance:
function getCookie(name) {
var cookie = "; " + document.cookie + ";";
var search = "; " + encodeURIComponent(name) + "=";
var value_start = cookie.indexOf(search);
if (value_start == -1) return "";
value_start += search.length;
var value_end = cookie.indexOf(';', value_start);
return decodeURIComponent(cookie.substring(value_start, value_end))
}
You need to remove possible white space around the cookie key before comparing to the string "lastvisit". This is done conveniently using regular expressions. /^\s+/ matches all white space at the beginning, /\s+$/ matches all white space at the end. The matches are replaced by the empty string, i.e. removed:
for( var i = 0 ; i < allCookies.length ; i++ ) {
var c = allCookies[i].split("="); // split only once
var key = c[0].replace(/^\s+/, '').replace (/\s+$/, ''); // remove blanks around key
if (key == "lastvisit") {
document.getElementById("last_visit").innerHTML = "You visited on " + c[1];
}
//...
}
hi i have a little problem with my javascript
can i make the simple way to execute content of array with different character of word?
for example :
var word = new Array();
word [0] = "is";
word [1] = "am";
.
.
.
.
word [100] = "when";
var word should be access with 3 ways,in order to reduce process to execute arrays..
first : " "+ word +" ";
second : " "+ word;
third : word +" ";
-thank you for helping-
I'm not exactly sure what you are chasing (fill me in and I'll update), but I'd like to point out a far better way of filling in that array literal...
var word = [
'is',
'am'
];
You can see the index is calculated automatically, and you are not required to repeat the var name for each member definition.
Update
Maybe you want something you can call and get the next array member each time. This should do it...
function getNextMember(array, startIndex) {
startIndex = startIndex || 0;
return function() {
startIndex++;
return array[startIndex];
};
};
var getNextWord = getNextMember(word);
alert(getNextWord() + ' ' + getNextWord());
See it on jsFiddle.
And of course, if you are feeling naughty, you could add that function to Array's prototype.