Skip to main content

查找指定内容

场景说明

在文档中查找指定的文本内容,并可以高亮显示查找结果。这是文档编辑中常用的功能。

适用场景:

  • 关键词查找和高亮
  • 内容定位
  • 敏感词检测
  • 文档内容分析

相关 API 文档

示例代码

全文查找并高亮

async function findAndHighlight() {
// 获取文档主文档区域
const content = Application.ActiveDocument.Content;

// 搜索并高亮文本"FilezOffice"
const success = await content.Find.execute('FilezOffice', true);
console.log('查找成功:', success);
}

查找但不高亮

async function findWithoutHighlight() {
const content = Application.ActiveDocument.Content;

// 搜索文本但不高亮显示(第二个参数为 false)
const success = await content.Find.execute('关键词', false);
console.log('查找完成:', success);
}

查找并返回匹配数量

async function findAndCount() {
const content = Application.ActiveDocument.Content;

// 查找文本并返回匹配项数量
// 参数: (查找文本, 是否区分大小写, 是否全词匹配)
const count = await content.Find.findData('文本', false, true);
console.log('找到的匹配项数量:', count);

return count;
}

区分大小写查找

async function findWithCaseSensitive() {
const content = Application.ActiveDocument.Content;

// 第二个参数为 true 表示区分大小写
const count = await content.Find.findData('Zoffice', true, false);
console.log('区分大小写查找结果:', count);
}

全词匹配查找

async function findWholeWord() {
const content = Application.ActiveDocument.Content;

// 第三个参数为 true 表示全词匹配
// 例如: 查找"office"不会匹配"FilezOffice"中的部分
const count = await content.Find.findData('office', false, true);
console.log('全词匹配结果:', count);
}

在选区中查找

async function findInSelection() {
// 通过 Selection 对象获取当前选区
const range = await Application.Selection.range;

// 在选区范围内查找
const count = await range.Find.findData('关键词', false, false);
console.log('在选区中找到:', count, '个匹配项');
}

清除查找高亮

async function clearHighlight() {
const content = Application.ActiveDocument.Content;

// 取消高亮显示
const success = await content.Find.clearHitHighlight();
console.log('清除高亮成功:', success);
}

查找并高亮多个关键词

async function highlightMultipleKeywords() {
const keywords = ['文档', '内容', '查找'];
const content = Application.ActiveDocument.Content;

for (const keyword of keywords) {
await content.Find.execute(keyword, true);
}

console.log('多关键词高亮完成');
}

在书签中查找

async function findInBookmark() {
// 获取指定书签
const bookmark = await Application.ActiveDocument.Bookmarks.item('bookmarkName');
const range = await bookmark.range;

// 在书签范围内查找
const count = await range.Find.findData('查找文本', false, false);
console.log('在书签中找到:', count, '个匹配项');
}

注意事项

  • execute() 方法用于查找并可选择高亮显示结果
  • findData() 方法用于查找并返回匹配项数量
  • clearHitHighlight() 用于清除查找高亮
  • 可以在全文档、选区、书签等不同范围内查找
  • matchCase 参数控制是否区分大小写
  • matchWholeWord 参数控制是否全词匹配
  • 查找对象通过 Range.Find 属性获取
  • 高亮显示会在文档中标记所有匹配项