Charlie Melidosian
Charlie Melidosian

Reputation: 13

Google Apps Script Auto Capitalise

I have been struggling with a script I have been working on for a while. The problem is that when I run the script with text like:

Hi. apples are amazing.

I want to make only the a in apples capitalized, but instead the text comes out as:

Hi. Apples Are Amazing.

Here is the code:

function caps() 
{
var body = DocumentApp.getActiveDocument().getBody();
var text = body.editAsText()
var caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lower = "abcdefghijklmnopqrstuvwxyx";
//while (() != null) {
//var search = text.findText('. a')
//var start = replace - 1
//text.deleteText(start, replace)
//text.insertText(start, " A")//}
for(var i=0; i<caps.length; i++)
{
  var nextCaps = caps.charAt(i);
  var nextLower = lower.charAt(i);

  while (text.findText('. ' + nextLower) != null)
  {
    Logger.log(nextLower)
    Logger.log(nextCaps)

  var search = text.findText('. ' + nextLower)
  var replace = search.getEndOffsetInclusive()
  var start = replace - 1
  text.deleteText(start, replace)
  text.insertText(start, " " + nextCaps)

  }
//var nextChar = caps.charAt(i);

//Logger.log(nextLower)
}
}

Basically, the code looks for ". a" and replaces it with ". A" (same with b, c, d and so on). If anyone can help me with this it would be very much appreciated.

Upvotes: 1

Views: 2404

Answers (1)

Lbatson
Lbatson

Reputation: 1017

The below code follows your example where you want to capitalize the first letter after the end of the first sentence. So long as that is the case this regex and replace will do that for any letters.

var str = 'Hi. apples are amazing.';

var reg = /\.\s./;
function replacement(match) {
    return match.toUpperCase();
}

str = str.replace(reg, replacement);
Logger.log(str);

Upvotes: 3

Related Questions