Combine two paragraphs using Script Lab

61 Views Asked by At

I am new to Script Lab. I just discovered this tool yesterday and was trying to find and remove a new line or the end of a paragraph, but with no luck so far. In a RegEx context, I am trying to find \w\s\n which mean - one lowercase letter, then a space and then a new line. I tried to run this code

async function run() {
    await Word.run(async (context) => {
      const results = context.document.body.search("\w\s\n", { matchWildcards: true });
      results.load("length");
      await context.sync();
      results.items.forEach((word) => {
        // ideally i would end up something like this 'n[space][new line]' and then I want to remove the new line and end up only with 'n[space]'. How can I make this?
      });
      await context.sync();
    });
}

If someone can show me a working demo of find and replace this will also help me understood how this framework is working. Thanks.

1

There are 1 best solutions below

0
Dimitar On BEST ANSWER

I wanted to find all paragraphs in Word which have this regex \w\s\n, but regex does not work the same way in Word API as normal regex as mention by @Rick so I end up using other method to catch the paragraphs I needed. I saw every paragraph has a firstLineIndent of -18. So I made one if, trim the paragraph trimmed = currentPara.text.trim(); so I will get rid of the spaces at the back check if the last char is not . or ! or ? and then if all of this is true add the next paragraph to the current one like this currentPara.insertText(nextPara.text, "End"); then simply delete the next paragraph as I do not need it anymore - nextPara.delete();

And this is my working solution

async function run() {
  await Word.run(async (context) => {
    const paragraphs = context.document.body.paragraphs;
    paragraphs.load("items");
    await context.sync();

    let currentPara;
    let nextPara;
    let trimmed;
    let lastChar;
    for (let i = 0; i < paragraphs.items.length; i++) {
      currentPara = paragraphs.items[i];
      nextPara = paragraphs.items[i+1];
      trimmed = currentPara.text.trim();
      lastChar = trimmed[trimmed.length - 1];
      if (currentPara.firstLineIndent == -18 && lastChar != "." && lastChar != "!" && lastChar != "?") {
        currentPara.insertText(nextPara.text, "End");
        nextPara.delete();
        // here I change the current paragraph style
        currentPara.firstLineIndent = 18;
        currentPara.isListItem = false;
        currentPara.leftIndent = 0;
      }
    }
  });
}

Hope that helps someone else. From the 2 days working with Word API I can say there are some limitations, but with logic you can get to your goal.