Search code examples
javascripteventstinymce

Why Are My Function Calls Not Working in TinyMCE


So, I've been trying to get TinyMCE to automatically replace a double dash with a &mdash. With what I've found, the setup function works fine for the most part but the parts that call the function cause the TinyMCE editor to break. What I'm looking for is a way to use the "editor.onKeyUp.add" and the "editor.onChange.add" to call the function customProcess and not break the editor.

tinyMCE.init({
//...            
setup: function (editor) {
        var customProcess = function (editor) {
            var lastSelection = editor.selection.getBookmark(2, true), // Store last selection for later restoration
                content       = editor.getContent({ format: 'html'});  // Get content in HTML entity encoded format

            // RegEx replacements
            content = content.replace(/--/g, '—'); // Convert two dashes into —

            // Set content of iframe editor with modified string
            editor.setContent(content, { format: 'html' });

            // Restore selection
            editor.selection.moveToBookmark(lastSelection);
        };

        // Listen for change event
        editor.onChange.add(customProcess);

        // Listen for key up event
        editor.onKeyUp.add(customProcess);
    }
});

Solution

  • The textpattern plugin will do this for you with zero coding:

    https://www.tiny.cloud/docs/plugins/opensource/textpattern/#replacementspatterns

    Here is a running example using TinyMCE Fiddle: https://fiddle.tiny.cloud/M5haab

    If you type in 2 consecutive dashes and press the space bar you get the emdash.