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…
JavaScript
x
4
1
window.editor.model.document.on('change:data', () => {
2
3
});
4
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
JavaScript
1
11
11
1
ClassicEditor
2
.create(document.querySelector('#editor'))
3
.then(editor => {
4
editor.model.document.on('change:data', () => {
5
let content = editor.getData();
6
if (/@w+( |s)/gi.test(content)) {
7
content = content.replace(/@w+( |s)/gi, 'newString ')
8
editor.setData(content)
9
}
10
})
11
})
JavaScript
1
2
1
<script src="https://cdn.ckeditor.com/ckeditor5/34.0.0/classic/ckeditor.js"></script>
2
<div id="editor"></div>