Чтобы обойти ограничение поиска в 255 символов в рабочем столе Word API, я разбиваю длинные строки на доступные для поиска куски по 254 символа и помещаю их в объект «oSearchTerms». Затем я пытаюсь перебрать oSearchTerms, найти текст, выделить его, затем выполнить поиск следующего фрагмента и делать то же самое, пока все элементы в oSearchTerms не будут выделены. Проблема в том, что это не зацикливание. Он успешно проходит первую итерацию, но останавливается.
Я пробовал обильные вызовы context.sync (), возвращал true, возвращал context.sync () и т. Д., Которые вы увидите закомментированными ниже, чтобыбезрезультатно.
Я должен также указать, что он не показывает никаких ошибок. Цикл просто не зацикливается.
Нужно ли преобразовывать это в асинхронную функцию? Я хотел бы придерживаться ES5 и не использовать толстые функции стрелок.
Чего мне не хватает?
var fullSearchTerm = "As discussed earlier, one of the primary objectives of these DYH rules is to ensure that operators have at least one source of XYZ-approved data and documents that they can use to comply with operational requirements The objective would be defeated if the required data and documents were not, in fact, approved and Only by retaining authority to approve these materials can we ensure that they comply with applicable requirements and can be relied upon by operators to comply with operational rules which We believe there are differences between EXSS ICA and other ICA that necessitate approval of EVIS ICA."
function findTextMatch() {
Word.run(function(context) {
OfficeExtension.config.extendedErrorLogging = true;
var oSearchTerms = [];
var maxChars = 254;
var lenFullSearchTerm = fullSearchTerm.length;
var nSearchCycles = Math.ceil(Number((lenFullSearchTerm / maxChars)));
console.log("lenFullSearchTerm: " + lenFullSearchTerm + " nSearchCycles: " + nSearchCycles);
// create oSearchTerms object containing search terms
// leaves short strings alone but breaks long strings into
// searchable 254 character chunks
for (var i = 0; i < nSearchCycles; i++) {
var posStart = i * maxChars;
var mySrch = fullSearchTerm.substr(posStart, maxChars);
console.log( i +" mySrch: "+ mySrch);
var oSrch = {"searchterm":mySrch};
oSearchTerms.push(oSrch);
}
console.log("oSearchTerms.length: " + oSearchTerms.length +" oSearchTerm: "+ JSON.stringify(oSearchTerms));
// Begin search loop
// iterate over oSearchTerms, find and highlight each searchterm
for (var i = 0; i < oSearchTerms.length; i++) {
console.log("oSearchTerms["+i+"].searchterm: " + JSON.stringify(oSearchTerms[i].searchterm));
var searchResults = context.document.body.search(oSearchTerms[i].searchterm, { matchCase: true });
console.log("do context.sync() ");
context.load(searchResults);
return context.sync()
.then(function(){
console.log("done context.sync() ");
console.log("searchResults: "+ JSON.stringify(searchResults));
if(typeof searchResults.items !== undefined){
console.log("i: "+i+ " searchResults: "+searchResults.items.length);
// highlight each result
for (var j = 0; j < searchResults.items.length; j++) {
console.log("highlight searchResults.items["+j +"]");
searchResults.items[j].font.highlightColor = "red";
}
}
else{
console.log("typeof searchResults.items == undefined");
}
// return true;
// return context.sync();
});
//.then(context.sync);
//return true;
} // end search loop
})
.catch( function (error) {
console.log('findTextMatch Error: ' + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log('findTextMatch Debug info: ' + JSON.stringify(error));
}
});
}