By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,404 Members | 1,987 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,404 IT Pros & Developers. It's quick & easy.

Get position of word from html code given its start and end index calculated from

P: 1
I have
Expand|Select|Wrap|Line Numbers
  1. contenteditable
div and would like to know the index of character typed in it with respect to html code.
For example:

Expand|Select|Wrap|Line Numbers
  1. <div id="editableDiv" contenteditable="true">
  2.     the @twitter
  3. </div>
The sentence is formatted like this: the @twitter
I can calculate the string position in sentence using below sentence. This is called once @ keyed down (start index) and on space bar key down (end index - 1)

Expand|Select|Wrap|Line Numbers
  1. getCaretPosition : function(){
  2.        var element = document.getElementById("editableDiv");
  3.        var caretOffset = 0;
  4.        if (typeof window.getSelection != "undefined") {
  5.             var range = window.getSelection().getRangeAt(0);
  6.             var preCaretRange = range.cloneRange();
  7.             preCaretRange.selectNodeContents(element);
  8.             preCaretRange.setEnd(range.endContainer, range.endOffset);
  9.             caretOffset = preCaretRange.toString().length;
  10.         } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
  11.             var textRange = document.selection.createRange();
  12.             var preCaretTextRange = document.body.createTextRange();
  13.             preCaretTextRange.moveToElementText(element);
  14.             preCaretTextRange.setEndPoint("EndToEnd", textRange);
  15.             caretOffset = preCaretTextRange.text.length;
  16.         }
  17.         return caretOffset;
  18.     }
Start index is 5 and end index is 12 for the word @twitter in above sentence.

I would now like to get the index of the same word from innerHTML of the div
Expand|Select|Wrap|Line Numbers
  1. editableDiv
.

InnerHTML:
Expand|Select|Wrap|Line Numbers
  1. <b>the</b> @twitter
Input index of the word @twitter: (5,12)
Output ->
start Index : 12
end index: 19
Dec 31 '13 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.