How can I highlight elements that match a regex in CKeditor?

好久不见. 提交于 2019-12-04 02:23:43
noseratio

The following approach worked for me in the past for a similar task:

  1. Walk the DOM tree of the CKEditor document and combine all text nodes into a single string (let's call it S). Use CKEDITOR.dom.walker for that, this answer should help here. While walking the tree, build a collection of data structures (let's call it C) to store each text node object and the position of where its text starts within S.

  2. Run your regex against S.

  3. If the match is not found, stop.

  4. Otherwise, using C collection, locate the start text node (let's call it SN), and offset within it, corresponding to the start character position of the match string inside S.

  5. Using C collection, locate the end text node (let's call it EN), and offset within it, corresponding to the end character position of the match string inside S.

  6. Create a CKEDITOR.dom.range object and position it using SN as the start and EN as the end (startContainer/startOffset/endContainer/endOffset).

  7. Use CKEDITOR.dom.selection.selectRanges() to select the range from the previous step.

I wonder why don't you use a "reverse" Regex ofr the unhighlight command?

    editor.addCommand( 'highlightMustache', {
        exec: function( editor ) {
            editor.focus();
            editor.document.$.execCommand( 'SelectAll', false, null );
            var mustacheRegex = /{{\s?([^}]*)\s?}}/g;
            var data = editor.getData().replace(mustacheRegex, '<span style="background-color: #FFFF00">{{ $1 }}</span>');
            editor.setData( data );
        }
    });

    // command to unhighlight mustache parameters
    editor.addCommand( 'unhighlightMustache', {
        exec: function( editor ) {
            editor.focus();
            editor.document.$.execCommand( 'SelectAll', false, null );
            var mustacheRegex = /<span style="background-color: #FFFF00">{{\s?([^}]*)\s?}}<\/span>/g;
            var data = editor.getData().replace(mustacheRegex, '{{ $1 }}');
            editor.setData( data );
        }
    });

It should work fine!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!