Jens Præst
Jens Præst

Reputation: 71

find the length of a string in google script

I'm trying to make a script for google sheet, who can count a letter in a text. But it seems that .length doesn't work. Anyone who can give directions on where to find the the solution.

    function Tjekkode(tekst , bogstav){
    var test = "";
    // find the length of laengdeTekst
    var laengdeTekst = tekst.length;
    var t = 0;
    // through the text character by character
    for ( var i = 1; i<laengdeTekst ; i++) {

     var test = tekst.substr(i,1);
     if (test == bogstav) {
      // if the letter is found, it is counted up
      // REMEMBER == means compare
      var t = t + 1;
     }
    }
    // returns percent appearance of the letter
    Return = t / længdeTekst * 100
    }

Thanks in advance

Upvotes: 6

Views: 49170

Answers (3)

Max Makhrov
Max Makhrov

Reputation: 18707

length is ok in your code. To test it, run this script:

function test( ) {

   var test = "123456";
   // finder længden på teksten
   var laengdeTekst = test.length;
   Logger.log(laengdeTekst);
}

After you run it, check Log, press [Ctrl + Enter]


The correct code in your case:

function Tjekkode(tekst, bogstav) {
  var test = "";

  var laengdeTekst = tekst.length;
  var t = 0;
  
  // start looping from zero!
  for ( var i = 0; i<laengdeTekst; i++) {

    var test = tekst.substr(i,1);
    if (test == bogstav) {
      var t = t + 1;
    }
  }

  // JavaScript is case sensitive: 'return != Return'
  return t / laengdeTekst * 100;  
}

Please, look at this tutorial for more info

Upvotes: 8

rdodhia
rdodhia

Reputation: 350

This is the google script that worked for me. Note the 24 - that's the length of an empty message that has markup like <div>...</div>

function TrashEmptyDrafts() {
  var thread = GmailApp.getDraftMessages();
  for (var i = 0; i < thread.length; i++) {
    b=thread[i].getBody();

    if (b.length <= 24.0){
      thread[i].moveToTrash();
    }  
  }}

Upvotes: 0

Jens Pr&#230;st
Jens Pr&#230;st

Reputation: 71

thanks I'll guess that I might get the one with the R instead of r at the end, but the script didn't run that line, because it kinda stopped at the .length line :/

the comments in danish is for my pupils (I'm a teacher in elementary school)

I'll see if google wants to cooperate today :|

Upvotes: 0

Related Questions