Google Apps Script中isStrikethrough方法仅首段生效问题求助
问题
我写了一段Google Apps Script代码,用来从指定ID的文档里提取字符:带删除线的正常显示,不带删除线的加粗显示。文档里有3段混合了删除线和非删除线格式的文本,但代码里的listOfparagraph[paragraphIndex].editAsText().isStrikethrough(index)只在第一段正常工作,从第二段开始一直返回true,结果完全不对。我试过改文本内容、手动调索引,问题还是存在。
代码示例
function ot() { var listOfparagraph = DocumentApp.openById(theIdOfTheFile).getBody().getParagraphs(); // the number of char to find var c = 40; var paragraphIndex=0; var paragraph = listOfparagraph[paragraphIndex].getText().toString(); var massege= ''; var index =0; while(c>0) { if(listOfparagraph[paragraphIndex].editAsText().isStrikethrough(index)== false && paragraph[index]!=' ') { massege+="<b>"+paragraph[index]+"</b>"; c--; } else { massege+=paragraph[index]; } if(paragraph.length-1==index) { paragraphIndex++; index=0; paragraph=listOfparagraph[paragraphIndex].getText().toString(); } else { index++; } } }
测试文本(无删除线部分为斜体)
abc def ghij
bvfr hytg juyh
zxs edc nhyu
实际返回文本
abc def ghij
bvfr hytg juyh
zxs edc nhyu
解决方案
问题根源
原代码每次循环都重复调用editAsText()获取文本对象,切换段落时没有重新绑定当前段落的文本对象,导致索引判断逻辑混乱。另外,段落切换后的索引重置逻辑虽然没问题,但因为文本对象没有对应更新,导致isStrikethrough返回错误结果。
修正后的代码
function ot() { const doc = DocumentApp.openById(theIdOfTheFile); const paragraphs = doc.getBody().getParagraphs(); const targetCharCount = 40; let message = ''; let remainingChars = targetCharCount; let paraIndex = 0; while (remainingChars > 0 && paraIndex < paragraphs.length) { const currentPara = paragraphs[paraIndex]; const paraText = currentPara.getText(); const textObj = currentPara.editAsText(); // 一次性获取当前段落的文本操作对象 let charIndex = 0; while (charIndex < paraText.length && remainingChars > 0) { const char = paraText[charIndex]; // 空格直接添加,不消耗计数 if (char === ' ') { message += char; charIndex++; continue; } // 用当前段落的文本对象判断删除线 const hasStrikethrough = textObj.isStrikethrough(charIndex); if (!hasStrikethrough) { message += `<b>${char}</b>`; remainingChars--; } else { message += char; } charIndex++; } paraIndex++; } console.log(message); return message; }
核心改动
- 提前获取当前段落的
Text对象(textObj),避免重复调用editAsText()引发的对象引用问题 - 优化循环结构:先处理完单个段落内的所有字符,再切换到下一段落,逻辑更清晰
- 单独处理空格,确保空格不消耗目标字符计数,和原代码逻辑保持一致
- 增加段落边界判断,防止数组越界报错
内容的提问来源于stack exchange,提问作者עדוא טייב
相关产品推荐
相关产品推荐

