在Google Scripts(Google Docs)中识别并提取段落对象加粗内容的方法
我来帮你搞定这两个Google Apps Script处理Google Docs段落格式的问题,直接上实用方案:
问题1:识别Paragraph对象中特定文字是否为加粗格式
Google Docs的段落(Paragraph)其实是由多个属性一致的文本片段组成的——比如一段里既有普通文本又有加粗文本,就会被拆分成不同的Text片段。要检测特定文字是否加粗,核心思路是遍历段落里的所有属性片段,检查每个片段的文本是否包含目标内容,同时判断该片段是否为加粗格式。
这里给你写个实用函数:
function isSpecificTextBold(paragraph, targetText) { // 获取段落中所有属性一致的文本片段数组 const attributeRuns = paragraph.getTextAttributeRuns(); for (let i = 0; i < attributeRuns.length; i++) { const textRun = attributeRuns[i]; const runText = textRun.getText(); // 检查当前片段是否包含目标文字,且该片段是加粗的 if (runText.includes(targetText) && textRun.isBold()) { return true; } } // 遍历完所有片段都没找到匹配的,返回false return false; }
使用的时候,你可以这样调用(比如获取文档里的第一个段落,检测"Joe"是否加粗):
const doc = DocumentApp.getActiveDocument(); const firstParagraph = doc.getBody().getParagraphs()[0]; console.log(isSpecificTextBold(firstParagraph, "Joe")); // 输出true或false
问题2:检测段落是否存在加粗部分并提取加粗文字
针对你举的例子"President: Joe Obam",我们可以遍历段落的属性片段,把所有加粗的文本片段收集起来,同时判断是否存在加粗内容。
函数示例如下:
function extractBoldTextFromParagraph(paragraph) { const attributeRuns = paragraph.getTextAttributeRuns(); let boldTexts = []; for (let i = 0; i < attributeRuns.length; i++) { const textRun = attributeRuns[i]; if (textRun.isBold()) { boldTexts.push(textRun.getText()); } } // 返回一个对象,包含是否有加粗内容和提取到的加粗文字 return { hasBold: boldTexts.length > 0, boldText: boldTexts.join("") // 如果多个加粗片段,拼接成完整文本 }; }
调用示例:
const doc = DocumentApp.getActiveDocument(); const targetParagraph = doc.getBody().getParagraphs()[0]; const result = extractBoldTextFromParagraph(targetParagraph); if (result.hasBold) { console.log("段落存在加粗内容,提取到的加粗文字:" + result.boldText); } else { console.log("段落中没有加粗内容"); }
比如如果段落里"Joe Obam"是加粗的,这个函数就会返回{hasBold: true, boldText: "Joe Obam"}。
内容的提问来源于stack exchange,提问作者ayjay
相关产品推荐
相关产品推荐

