title: Alternative Ways To Track Position In Changing String
body: <p>Currently, I am using an array to keep track of a unique key that is tagged to different caret positions in a string.  The array's keys are the position, and the value is the unique key.</p>
  
  <pre><code>Sample Array
  
  [4]  =&gt;   RED
  [8]  =&gt;   BLUE
  [12] =&gt;   ORANGE
  </code></pre>
  
  <p>Sample String: </p>
  
  <p>The red dog is howling</p>
  
  <p>Each time the string is edited, the caret positions that occur after the change point shift.  (ie: if I change the string to "A red dog is howling", my script will subtract 2 from each key to re position the caret positions to the modified string.</p>
  
  <p>In slow editing, or short strings this is fine, however slower browsers often mix up the key positions on longer strings because it takes too long to update each key (50 - 100 keys).</p>
  
  <p>Here is my psuedo script:</p>
  
  <pre><code>textLength = 22; // SET FROM INIT
  
  $('#text').onkeyup(function(){
  
      currentPosition = getCaretPosition(); // Returns caret position
      newArray = [];
      movePos = (document.getElementById('text').length - textLength);
  
      for(var i=0; i&lt;sampleArray.length; i++){
          if(i &gt;= currentPosition){
              newArray[i+movePos] = sampleArray[i];
          }else{
              newArray[i] = sampleArray[i];
          }
      }
      sampleArray = newArray;
  
      textLength = document.getElementById('text').length;
  
  });
  </code></pre>
  
  <p>I realize that asking "Is there a better way to do this" could be quite subjective, however let me rephrase that by asking "What other ways are out there to accomplish the same re-indexing of keys based on changes to the initial string that may be more efficient"</p>
  
  <p>Just to be clear, the expected behavior is to always have sampleArray keys tracking the initial position in the string relative to the words they are tagged to even if other words are added before or after.  In the example I gave, the first key is attached just before the word "red", the second key is attached just before the word "dog", and the third key is attached before the word "howling".</p>