Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsstring-length

google apps script counting characters in a cell


I am trying to find a way to adjust a merged cell group to show all text characters that were contained in the first cell when merged. I thought there would be a simple way to count the number of characters in that first cell and then I can adjust the height of a cell or cells by developing a formula (such as add .2 for each 30 characters).

I am using the following code to try and count the characters:

var tempValue;
var tempCount = 0;

    tempValue = sprintSheet.getRange("D3").getDisplayValue();
    tempCount = tempValue.length();

Unfortunately, I get the following error on the last line:

TypeError: Cannot call property length in object

I can't seem to make the transition from range / value to text to use the length property.


Solution

  • Short answer

    Use tempCount = tempValue.length instead of tempCount = tempValue.length();

    Explanation

    Google Apps Script is based on JavaScript. The getDisplayValue() returns an a JavaScript string primitive. A primitive data type can use the the length property, and its called by using .length, (note that parenthesis are not used).

    References