How to Search a word through coding in CKEditor using javascript?

ぐ巨炮叔叔 提交于 2019-12-24 06:28:17

问题


Can anyone give tell me how to search for a particular word in a CKEditor instance using JavaScript? I have one button named search and one textbox. When I type a word in the text box and press the button it should find the text in the Editor. The solution must be JavaScript only.


回答1:


There's a command find, however editor.execCommand( 'find' ) will only show the find&replace dialog, what rather won't satisfy you.

Unfortunately, to copy behaviour of this dialog you'll need to write your own search impl, because logic standing behind it is unreachable from outside (this needs a ticket on http://dev.ckeditor.com). You can check find plugin impl in _source/plugins/find/dialogs/find.js, but it probably won't help you enough without some explanation.

So what do you need to do?

First - you need to find in which text nodes exactly and at what positions your text is - this won't be trivial :). You have to start from editor.document.getBody() and then traverse DOM tree in source order. There's a tool that can help you - CKEDITOR.dom.walker.

Second - you need to create Range (new CKEDITOR.dom.range( editor.document )) and set its startContainer, startOffset, endContainer, endOffset. Here's more about W3C's ranges - http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html - CKEDITOR's are quite similar - you can find more about them in API docs (sorry for not posting the link, but with my low reputation I can't :D).

And when you set start and end of the range you just have to call range.select(). If editor was focused (you can ensure this by calling editor.focus()) range will be selected.




回答2:


Extract the text inside the CKEditor into a variable (I wouldn't be surprised if CKEditor provides that functionality by itself), and then run the function .indexOf(SubstringToFind) on the extracted text.




回答3:


You can extract the data from a CKEditor instance using instance.GetData().

How you find the word is up to you, if it's simple you can just use .indexOf() as @TomTeman suggests, otherwise you might want a regex.



来源:https://stackoverflow.com/questions/10996938/how-to-search-a-word-through-coding-in-ckeditor-using-javascript

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