'How to get a range from start & end index with Office.js while developing MS Word Add-in

I want to get a sub range by character index from the parent paragraph. What's the suggest way to do so? The only method I found to shrink the range is "Paragraph.search()"

ref: Word.Range: https://docs.microsoft.com/en-us/javascript/api/word/word.range?view=office-js Word.Paragraph: https://docs.microsoft.com/en-us/javascript/api/word/word.paragraph?view=office-js

My use case:

I'm writing a markdown plugin for MS Word and I'm trying to parse the following paragraph.

A **bold** word

The output from markdown parser is {style:"strong",start:2,end:9}. So I want to apply bold style to the targeting range.



Solution 1:[1]

Found a way just now. The key is passing an empty separator to Paragraph.getTextRanges([""]) I'm not sure how bad the performance would be.

const makeBold = async (paragraph:Word.Paragraph,start:number,end:number) => {
  const charRanges = paragraph.getTextRanges([""])
  charRanges.load()
  await charRanges.context.sync()
  const targetRange = charRanges.items[start].expandTo(charRanges.items[end])
  targetRange.load()
  await targetRange.context.sync()
  targetRange.font.bold = true
  await targetRange.context.sync()
}

Solution 2:[2]

The existing answer didn't work for me (it seems like getTextRanges() no longer accepts empty strings).

So I have adapted the answer to use paragraph.search() instead.

async function getRangeByIndex(paragraph: Word.Paragraph, start: number, end: number) {
    const charRanges = paragraph.search('?', { matchWildcards: true })
    charRanges.load()
    await charRanges.context.sync()

    const targetRange = charRanges.items[start].expandTo(charRanges.items[end])
    targetRange.load()
    await targetRange.context.sync()

    return targetRange
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jason Song
Solution 2