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

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.

网友答案:

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.

网友答案:

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.

网友答案:

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.