Reputation: 478
Right now I am locating the words in a Word document by searching the term using
context.document.body.search(dict, { ignorePunct: true, matchCase: true, matchWholeWord: true });`
But I want to locate a word by its ordinal position in the Word document. I can't find the exact nth
word.
Is it possible to do that?
Upvotes: 0
Views: 97
Reputation: 5046
Speedy: You can use the range.split() method for this. (i.e. this applies to searchResult, body, paragraph, content control, etc.) Assuming that you want to get the 4th word in the paragraph this is how you do it:
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);
});
}
and if you want to play with it in Script lab here is the gist you can import.
Upvotes: 1
Reputation: 25693
The Office JS APIs don't (yet) have an equivalent to the Word COM object Words
that lets you specify a "word" in a given range via an index value. Considering the fact that words are separated by a space you can get the entire text of a document, then split it to an array of "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]);
});
Once you know what that nth
word is, you can use the code you already have to search/find the range in the document.
If the word could occur more than once then you may need to expand how the "split" is used in order to get the surrounding words so that the search can be more accurate.
Upvotes: 0