问题
I have the following use case using Office.js:
- search for some text with
body.search()
- after finding the text, can be multiple occurrences, iterate through them and replace them with a ContentControl with a different content
The search part is easy, but I'm not sure about the second part. Inserting a ContentControl to the cursor position and manipulating it's HTML content isn't an issue, but I'm not sure if it's possible to programmatically select a string and then replace it with other content. Is it? Or should I somehow create a ContentControl around the selected text and then just manipulate it's HTML content?
This is my code so far, within Word.run
:
const res = context.document.body.search('[{]*[}]', {matchWildCards: true});
context.load(res, 'text');
return context.sync().then(() => {
const citeKeys = [];
for (let i = 0; i < res.items.length; i += 1) {
// iterate through found strings by accessing res.items[i].text
}
// ...
回答1:
After you searched the strings, body.search will return a collection to you and you can loop the range collection and call range.insertText("...", "replace")
. This insertText
method will also return a range
and then you can call range.insertContentControl
on it. I think this will help you achieve the goal.
来源:https://stackoverflow.com/questions/50943435/office-js-select-text-and-replace-it-with-a-contentcontrol