现在,我通过使用搜索词来定位 Word 文档中的词
context.document.body.search(dict, { ignorePunct: true, matchCase: true, matchWholeWord: true });`
但我想通过它在 Word 文档中的序号位置来定位一个单词。我找不到确切的nth
词。
有可能这样做吗?
现在,我通过使用搜索词来定位 Word 文档中的词
context.document.body.search(dict, { ignorePunct: true, matchCase: true, matchWholeWord: true });`
但我想通过它在 Word 文档中的序号位置来定位一个单词。我找不到确切的nth
词。
有可能这样做吗?
Speedy:您可以为此使用 range.split() 方法。(即这适用于 searchResult、正文、段落、内容控制等)假设您想获得段落中的第 4 个单词,您可以这样做:
async function run() {
await Word.run(async (context) => {
//the method returns an array with the split ranges...
// the first parameter is an array of the delimiters you want to use, in this case the space. you can add more if needed.
let myWords = context.document.body.paragraphs.getFirst().split([" "], true, true);
myWords.load();
await context.sync();
if (myWords.items.length >= 3) // just because i want the 4th word :)
console.log(myWords.items[3].text);
});
}
如果您想在 Script lab 中使用它,这里是您可以导入的要点。
Office JS API(还)没有与 Word COM 对象等效的对象Words
,它允许您通过索引值在给定范围内指定“单词”。考虑到单词由空格分隔的事实,您可以获得文档的整个文本,然后将其拆分为“单词”数组。
await Word.run(async (context) => {
let ordinalWord = 2;
let rng = context.document.body;
rng.load("text");
await context.sync();
let sContent = rng.text;
let words = sContent.split(" ", ordinalWord);
console.log(words[ordinalWord - 1]);
});
一旦你知道那个nth
词是什么,你就可以使用你已经拥有的代码来搜索/查找文档中的范围。
如果单词可能出现多次,那么您可能需要扩展“拆分”的使用方式,以便获取周围的单词,以便搜索更准确。