问题
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