ckeditor demo
by ocanal
HTML
<script src="//cdn.ckeditor.com/4.5.1/standard/ckeditor.js"></script>
<textarea name="editor1" id="editor1" rows="10" cols="80">test Friends was only an okay show some other words and the magic phrase again Friends is the best series ever and other words again</textarea>
<br/>
<button>Convert</button>
JavaScript
var phrases = ['Friends was only an okay show', 'Friends is the best series ever'];
var styles = [
'background-color: red',
'color:yellow'
];
phrases = phrases.map(function(item) {
return '((?<![\\w\\d])'+item+'(?![\\w\\d]))'
});
CKEDITOR.editorConfig = function(config) {
config.language = 'es';
config.uiColor = '#F7B42C';
config.height = 300;
config.toolbarCanCollapse = true;
};
CKEDITOR.replace('editor1', {
extraAllowedContent: 'span{*}(*)',
on: {
instanceReady: function( evt ) {
// your stuff here
}
}
});
var e = CKEDITOR.instances['editor1'];
e.on('blur', changeEvent);
e.fire('blur');
function changeEvent(ev) {
var html = e.getData();
var re = new RegExp('(' +phrases.join('|') + ')', 'gi');
var newHtml = html.replace(/(<span(?: \w+="[^"]+")* class="matched-content"(?: \w+="[^"]+")*>([^<]*)<\/span> )/g, '\$2');
console.log(newHtml);
newHtml = newHtml.replace(re, function(matched) {
return '<span class="matched-content" style="'+ styles.join(';') +'">'+matched+'</span>'
});
if (newHtml != html) {
ev.removeListener();
e.setData(newHtml, function() {
var range = e.createRange();
range.moveToElementEditEnd(range.root);
e.getSelection().selectRanges([range]);
e.on('blur', changeEvent);
});
}
}