I've got the following code to find a piece of text in IE11
var search_position = 0;
function findMyText(find)
{
// create range (selects all text)
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById("editor"));
if(search_position == 0)
{
range.moveStart("word", 0);
range.findText(find);
}
// find the nth word that matches, where n is search_position
for (var i = 0; i < search_position; i++)
{
range.moveStart("word", 1);
range.findText(find);
}
search_position++;
range.select();
var l = range.text.length
if(l < find.length)
{
search_position = 0;
}
}
This finds each successive instance of find
and selects it. It works by finding the first instance of a piece of text, marking the search index and then moving to the next word.
What I really want to do is start from a certain cursor position without looping through all the text. As in, if the user places the cursor in the middle of the text, I want to search from that point on. I also want to add a replace function. I can move to a specific character position like this
range.moveStart("character", x);
Where x is the character position. I can fetch this character position from the cursor position using the following code.
function getCaretPosition() {
var ie = (typeof document.selection != "undefined" && document.selection.type != "Control") && true;
var w3 = (typeof window.getSelection != "undefined") && true;
var caretOffset = 0;
if (w3) {
var range = window.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(editor);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
else if (ie) {
var textRange = document.selection.createRange();
var preCaretTextRange = document.body.createTextRange();
preCaretTextRange.expand(editor);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
What I can't do, and need to, is find the current start position of my range. I need to know this for my replace method to work correctly. When I replace a word, I need to know where I am in the document.
range.startOffset
returns undefined. So how do I get the position?