Skip to content
Advertisement

CKEditor 5, jQuery – find and replace text

How could I find and replace text in CKEditor 5 using JavaScript and jQuery?

I want to find special character ‘@’ in the text and replace all characters after ‘@’ and ‘@’ character too on my own text.

I am using change:data

window.editor.model.document.on('change:data', () => {

});

Advertisement

Answer

you need editor.getData() and editor.setData(), then use Regex @w+  to match @, alphanumeric and space, without matching space it only work on paste but you can’t type @user because when typing @u it will replaced with newString

the example below

ClassicEditor
  .create(document.querySelector('#editor'))
  .then(editor => {
    editor.model.document.on('change:data', () => {
      let content = editor.getData();
      if (/@w+( |s)/gi.test(content)) {
        content = content.replace(/@w+( |s)/gi, 'newString ')
        editor.setData(content)
      }
    })
  })
<script src="https://cdn.ckeditor.com/ckeditor5/34.0.0/classic/ckeditor.js"></script>
<div id="editor"></div>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement