Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 894
Jens Præst Avatar asked Apr 12 '16 13:04

Jens Præst


1 Answers

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

like image 144
Max Makhrov Avatar answered Sep 21 '22 04:09

Max Makhrov