Word JS APIs: extending a Range

后端 未结 1 1793
醉梦人生
醉梦人生 2021-01-29 12:16

While working on answering this question I would really like to have been able to extend a Range by a specific number of characters. In the COM API I would have used Range

1条回答
  •  被撕碎了的回忆
    2021-01-29 12:51

    That was something we had in the original design, but it was actually removed from the API as it can easily lead to unexpected outcomes (i.e. hidden character inconsistencies, footnotes, etc.), and we could not cover those cases with the resources at hand. We decided to remove it.

    That been said I think you can achieve something similar to range.MoveEnd() with Word.js, you just need to define to the end of what ;). One way of doing it is to use the range.expandTo(endRange) method. Again, The interesting thing is how to get the "endRange", so the following example shows how to do it if "end" means the end of the paragraph, probably in your scenario will suffice.

    async function run() {
        await Word.run(async (context) => {
            //assume the range at the end of your 255 characters.
            var startRange = context.document.getSelection().getRange("end"); 
            //This one is the range at the end of the paragraph including the selection.
            var endRange = context.document.getSelection().paragraphs.getLast().getRange("end");
    
            var deltaRange = startRange.expandTo(endRange);
            context.load(deltaRange);
    
            await context.sync();
            // this will print the characters after the range all the way to the end of the paragraph.
            console.log(deltaRange.text);
        });
    }

    hope this helps or at least sets you up in the right direction.

    0 讨论(0)
提交回复
热议问题