2012-07-13 17 views
6

Me gustaría encontrar todas las instancias de una palabra en un documento de Google y destacarlas (o comentar, cualquier cosa que se destaque). He creado la siguiente función, pero solo encuentra la primera aparición de la palabra ("el" en este caso). ¡Cualquier idea sobre cómo encontrar todas las instancias de la palabra sería apreciada!Búsqueda de texto (varias veces) y resaltado

function findWordsAndHighlight() { 
var doc = DocumentApp.openById(Id); 
var text = doc.editAsText(); 
//find word "the" 
var result = text.findText("the"); 
//change background color to yellow 
result.getElement().asText().setBackgroundColor(result.getStartOffset(),    result.getEndOffsetInclusive(), "#FFFF00"); 
}; 

Respuesta

0

Bueno, javascript simple es suficiente,

var search = searchtext; 
var index = -1; 

while(true) 
{ 
    index = text.indexOf(search,index+1); 

    if(index == -1) 
    break; 
    else 
    /** do the required operation **/ 
} 

Espero que esto ayude!

+0

Gracias por su ayuda, balajiboss. Lamentablemente, errores en index = text.indexOf (búsqueda, índice + 1); con error: No se puede encontrar la función indexOf en el objeto Texto. – user1523207

+0

indexOf funciona en cadenas. Puede usar el método getText() para obtener el texto del documento como una cadena. – balajiboss

1

autorización así, el encadenamiento de sus códigos podría terminar como esto:

function findWordsAndHighlight() { 
var doc = DocumentApp.openById("DocID"); 
var text = doc.editAsText(); 
var search = "searchTerm"; 
var index = -1; 
var color ="#2577ba"; 
var textLength = search.length-1; 

while(true) 
{ 
    index = text.getText().indexOf(search,index+1); 
    if(index == -1) 
    break; 
    else text.setForegroundColor(index, index+textLength,color); 
} 

}; 

todavía tengo duda. Este código funciona bien, pero ¿por qué tengo que usar search.length-1?

1

Con la introducción de scripts en documentos, ahora es posible hacer una función de resaltado de texto que se invoca desde un menú personalizado.

Esta secuencia de comandos se modificó a partir del uno en this answer, y se puede llamar desde la interfaz de usuario (sin parámetros) o una secuencia de comandos.

/** 
* Find all matches of target text in current document, and highlight them. 
* 
* @param {String} target  (Optional) The text or regex to search for. 
*       See Body.findText() for details. 
* @param {String} background (Optional) The desired highlight color. 
*       A default orange is provided. 
*/ 
function highlightText(target,background) { 
    // If no search parameter was provided, ask for one 
    if (arguments.length == 0) { 
    var ui = DocumentApp.getUi(); 
    var result = ui.prompt('Text Highlighter', 
     'Enter text to highlight:', ui.ButtonSet.OK_CANCEL); 
    // Exit if user hit Cancel. 
    if (result.getSelectedButton() !== ui.Button.OK) return; 
    // else 
    target = result.getResponseText(); 
    } 
    var background = background || '#F3E2A9'; // default color is light orangish. 
    var doc = DocumentApp.getActiveDocument(); 
    var bodyElement = DocumentApp.getActiveDocument().getBody(); 
    var searchResult = bodyElement.findText(target); 

    while (searchResult !== null) { 
    var thisElement = searchResult.getElement(); 
    var thisElementText = thisElement.asText(); 

    //Logger.log(url); 
    thisElementText.setBackgroundColor(searchResult.getStartOffset(), searchResult.getEndOffsetInclusive(),background); 

    // search for next match 
    searchResult = bodyElement.findText(target, searchResult); 
    } 
} 

/** 
* Create custom menu when document is opened. 
*/ 
function onOpen() { 
    DocumentApp.getUi().createMenu('Custom') 
     .addItem('Text Highlighter', 'highlightText') 

     .addToUi(); 
} 
+0

Respuesta duplicada a una pregunta muy similar. Consulte [aquí] (http://stackoverflow.com/questions/12064972/can-i-color-certain-words-in-google-document-using-google-script/16924466#16924466). – Mogsdad

8

Sé que esto es un antiguo, pero así es como agrego efectos al texto en Google Script. El siguiente ejemplo es específicamente para agregar resaltado a todas las ocurrencias de una cadena en particular en un documento.

function highlightText(findMe) { 
    var body = DocumentApp.getActiveDocument().getBody(); 
    var foundElement = body.findText(findMe); 

    while (foundElement != null) { 
     // Get the text object from the element 
     var foundText = foundElement.getElement().asText(); 

     // Where in the Element is the found text? 
     var start = foundElement.getStartOffset(); 
     var end = foundElement.getEndOffsetInclusive(); 

     // Change the background color to yellow 
     foundText.setBackgroundColor(start, end, "#FCFC00"); 

     // Find the next match 
     foundElement = body.findText(findMe, foundElement); 
    } 
} 
Cuestiones relacionadas