Luke Barrier
Luke Barrier

Reputation: 51

google app script not rendering my translated message

function enes() {   
var doc = DocumentApp.getActiveDocument()   
var text = doc.getSelection()   
var sourceLanguage = 'en'   
var targetLanguage = 'es'   
var replacement = LanguageApp.translate(text, sourceLanguage, 
targetLanguage)   
console.log(text + '=' + replacement)
}

This should log the selected text in console with the translation to Spanish but isn't for some reason. Please Help!

Upvotes: 0

Views: 104

Answers (1)

webstermath
webstermath

Reputation: 599

The issue with your code is that the first argument of LanguageApp.translate() requires a string type and Document.getSelection() returns a Range Object. To get the text string out of the Range you can use the following code:

function enes() {   
var doc = DocumentApp.getActiveDocument()   
var text = doc.getSelection()
.getRangeElements()[0]
.getElement()
.asText()
.getText();
var sourceLanguage = 'en'   
var targetLanguage = 'es'   
var replacement = LanguageApp.translate(text, sourceLanguage, 
targetLanguage)   
Logger.log(text + '=' + replacement)
}

Note: I replaced console.log() with the native Logger.log() for testing convenience.

Additionally note: This will only return the first RangeElement. If you have more you can loop through them with something like:

function enes() {   
var doc = DocumentApp.getActiveDocument()   
var text = doc.getSelection()
.getRangeElements().getRangeElements().reduce(function(acc,rangeElement){
    return acc+rangeElement
    .getElement()
    .asText()
    .getText();
},"");
var sourceLanguage = 'en'   
var targetLanguage = 'es'   
var replacement = LanguageApp.translate(text, sourceLanguage, 
targetLanguage)   
Logger.log(text + '=' + replacement)
}

Upvotes: 1

Related Questions