Office.js select text and replace it with a ContentControl

有些话、适合烂在心里 提交于 2019-12-24 07:18:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!