Sri Vathsav
Sri Vathsav

Reputation: 13

finding length of a sentence in a cell, in google apps script

I'm pretty new to this scripting and all, I want to find the length of a sentence in a cell in google sheet. Example, "I want to check the length" is a sentence in cell A1 in google sheet, I want to find the length of this string.

And one more, if I want to replace text like space(" ") with any thing like plus (+), I have used script as shown below

var newdata = olddata.toString().replace(" ","+");

// here old data refers to the string "I want to check length"

// output that displayed in log is like "I+want to check length"

// Output, that I want i like "I+want+to+check+length"

when I used this, in log I can see only, first space is getting replaced in the whole string/sentence. so how can modify/alter my code in order to replace all the spaces with any desired character.

Upvotes: 1

Views: 760

Answers (1)

Rahul Bhobe
Rahul Bhobe

Reputation: 4451

The length of the string is given by newString.length property.

let oldString = "I want to check the length";
console.log(oldString.length);

The replace() function uses regular expressions to replace the strings. To replaces all matched patters, you will need to use /g global match. To match all spaces, you need to provide /\ /g to the replace() function. See example:

let oldString = "I want to check the length";
let newString = oldString.replace(/\ /g, "+");
console.log(newString);
console.log(newString.length);

Upvotes: 1

Related Questions