bykovenator
bykovenator

Reputation: 3

How to use String.replace() method without messing up blank paragraphs and object identifiers in MS Word 2013?

I am writing an app for MS Word 2013, which changes formatting of all dates in the selected text to a certain format. Here's a stripped-down version of the code, which looks for mm-dd-yyyy dates and changes them to dd.mm.yyyy dates once the text is selected from the document and button is clicked in the app.

(function () {
    "use strict";

    Office.initialize = function (reason) {
        $(document).ready(function () {
            app.initialize();
            $('#get-data-from-selection').click(getDataFromSelection);
        });
    };

    function getDataFromSelection() {
        Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
            function (result) {
                var output = 
                    result.value.replace(/(\d\d)-(\d\d)-(\d\d\d\d)/g, '$2.$1.$3');
                Office.context.document.setSelectedDataAsync(output);                
            }
         );
    }
})();

The problem I run into is that when table or text box is included into selection it is getting converted to regular text. For example: screenshot 1

When I select text before the table and include carriage return of the last line of text before the table into selection, all the selected text jumps into the top left cell of the table. screenshot 2

At the same time if I only select cells of the table, nothing happens when I call the app.

As for text inside text box, it disappears when text box is included into larger selection, but if only text inside text box is selected, everything works fine.

Briefly, an input to my code is a selection in the document, containing 3 regular paragraphs, a table, and a text box. The output should be same as input with dates format changed from mm-dd-yyyy to dd.mm.yyyy. The structure of the document should remain the same.

Please hint me on what I am doing wrong. I have been looking for answer for a while, but could not find the solution. Thank you!

Upvotes: 0

Views: 78

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25663

The problem is that you're using the CoercionType "plain text", so Word is doing its best to give you that. This means the underlying structures of the Word document are being removed before being handed over to your code for processing.

And then you're writing this plain text back into the document, replacing the selection. In some instances, that will result in replacing the document structures. In other instances Word is deciding it won't do that, so nothing happens.

If you want to do something like this "wholesale" you need to work with a CoercionType that retains Word's underlying structures as well as any formatting that might be present. The HTML CoercionType might help, but best would certainly be OOXML (the Office Open XML file format).

Upvotes: 1

Related Questions