How to get range of the text in Word document programmatically in MS Office Word add-in using JS API [duplicate]

情到浓时终转凉″ 提交于 2020-01-22 02:16:18

问题


I need to get numerical range of the text(example: startpoint-30, endpoint-35) in word document programmatically (via MS Office add-in), but I can't find how to do that via JS. Here is an example:

Hello my friend Pete, I talked to your friend Robert yesterday and he told about his friend Ann.

So, I need to get range of any word i want and create array of word`s ranges for future development. For example if we speak about word "Pete" the range of it should be (16,20), if the beginning of the text is 0. When I researched this on the Internet I've found some info that it seems to be impossible to do with JS API.

But i found such functionality in .NET docs. Here is the link https://docs.microsoft.com/en-us/visualstudio/vsto/how-to-programmatically-define-and-select-ranges-in-documents?view=vs-2019

So the final question. Is it possible(if yes, is it very complicated and how can I achieve that) to do such functionality that I've described above with JS API or I should switch to .NET not to waste my time.


回答1:


I'm assuming that you mean literally to get the numerical bounds of a range, not that you want to use numerical bounds that you already have to get a range. So if I understand what you want to do, then I recommend that you try the following:

Get a reference to the entire text as a Range object. Then use the Range.split method to get the range that precedes the "Pete". The text of first member of the ranges collection that is returned is "Hello my friend ". The length of this string is your start point. Your end point is the sum of the start point and the length of "Pete".

var target = "Pete";
var ranges = myRange.split([target], true, true, false);
var precedingRange = ranges.getFirst();
var startPoint = precedingRange.text.length;
var endPoint = starPoint + target.length; 


来源:https://stackoverflow.com/questions/59480003/how-to-get-range-of-the-text-in-word-document-programmatically-in-ms-office-word

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