Writing assistance features significantly speed up the writing process by providing auto-correction, auto-completion, and key phrase replacement, saving time and reducing errors to create a professional document or letter. In particular, pre-designed and phrased sentences that are inserted frequently improve the user experience of such applications.

This sample shows how to replace the word at the current input position with content retrieved from a Web API.


To simulate the phrase replacement, the following Web API method ReplaceWord accepts a string and returns a value from a dictionary:

public IActionResult ReplaceWord(string word) {
Dictionary<string, string> dict = new Dictionary<string, string>()
{ "Word1", "<strong>Formatted</strong> replacement for <em>Word1</em>" },
{ "Word2", "<strong>Formatted</strong> replacement for <em>Word2</em>" },
{ "Word3", "<strong>Formatted</strong> replacement for <em>Word3</em>" }
return dict.ContainsKey(word) ? Ok(dict[word]) : Ok(null);
view raw test.cs hosted with ❤ by GitHub

This Web API method is called from JavaScript in the asynchronous method replaceWord:

function replaceWord(word) {
return new Promise(resolve => {
$.get("home/replaceWord", { word: word })
.done(data => resolve(data))
.fail(() => resolve(null));
view raw test.js hosted with ❤ by GitHub

Replacing the Selection

When the user presses F8, the word at the input position is selected and retrieved. This word is then sent to the Web API to retrieve the replacement string. This string will eventually be loaded into the selection to replace the current string.

TXTextControl.addEventListener("textControlLoaded", async function () {
document.addEventListener("keydown", logKey);
async function logKey(e) {
if (e.key === "F8") {
const text = await getTextFromSelection();
const replacedText = await replaceWord(text);
if (replacedText !== undefined) {
await loadReplacedText(replacedText);
function getTextFromSelection() {
return new Promise(resolve => {
TXTextControl.selectWord(() => {
TXTextControl.selection.getText(text => resolve(text));
async function loadReplacedText(replacedText) {
const encodedText = btoa(replacedText);
await TXTextControl.selection.load(TXTextControl.StreamType.HTMLFormat, encodedText);
view raw test.js hosted with ❤ by GitHub

The following screen video shows the replacement in action.

Phrase replacement

You can test this yourself by downloading the Visual Studio project from our GitHub repository.