Get start index and end index for highlight using rangy-javascript
<p>I have array of misspelled words<code>(window.essaySpellingErrors)</code>.I have an essay text which is saved in the database from tinyMCE editor.<code>(data.data.essay)</code>.</p>

<p>I want to render this essay text in div for teacher so that teacher can evaluate the essay.</p>

<p>But the issue is that i am not able to highlight properly the misspelled words in the essay while rendering. Also i want the start index and end index of the first occurrence of every misspelled word.</p>

<p>So that next time whenever the essay loads the highlights can be made from the start index and end index i saved previously.</p>

<p>I am using rangy for highlight making with angular along with some javascript.</p>

<p>Here i am attaching the code which loops every element of the misspelled words.</p>

<p>Here <code>$scope.comments</code> indicates the comments which teacher makes on essay and loads everytime whenever teacher opens to evaluate essay.When there is no comment added in the system by default misspelled comments are added in the comment box.</p>

<pre><code>$scope.getEssayDetails = function(){
    // Set the essay content.
    // Write ajax call to get the essay content
    $http({
      method  : 'POST',
      url     : Helpers.constants['CONTROLLER_PATH'] + 'essayAllotment/getEssay',
      data    : $.param({'eMode':eMode ,'essayScoreID':eScoreID}), //forms user object
      headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} 
     }).success(function(data) {
            if(Helpers.ajax_response( '' , data , [] )){
                     $scope.getEvaluationEssay($.parseJSON(data.result_data));
              }
     }).error(onAjaxError);
};

$scope.getEvaluationEssay=function(data, extraParams)
{
    $("#essay_detail").html("");
    $scope.comments = [];
    $scope.togglecomment = false;
    $scope.comments = [];
    $scope.essayDetails = {};
    window.essaySpellingErrors=[];

    if(data.data.essaySpellingErrors!=undefined)
        window.essaySpellingErrors=data.data.essaySpellingErrors;
    data.data.essay=data.data.essay.replace(/&amp;nbsp+/ig,' ');

    //essayPlainText=data.data.essay.replace(/&lt;span class=\'sp_err\'&gt;(.*?)&lt;\/span&gt;/g,"$1");
    //essayPlainText=essayPlainText.replace(/&lt;span class=\'for_err\'&gt;(.*?)&lt;\/span&gt;/g,"$1");
    //essayPlainText=essayPlainText.replace(/\n/ig,' ');
    //essayPlainText=essayPlainText.replace(/\s+/ig,' ');

    essayPlainText=data.data.essay;
    $("#essay_detail").html(essayPlainText);

    if (data.data.report.selectFeedback != "") {
        var sfbck = data.data.report.selectFeedback.split('{|~|}');
        var commentStr;
        for (var i = 0; i &lt; sfbck.length; i++) {
            var sfbi = sfbck[i].split('|*|');
            if ((sfbi).length != 3) continue;
            sfbi.push(i);
            $scope.createCommentBox(sfbi);    
            var indexArr = sfbi[0].match(/\[(.*?)\]/);
            commentStr=indexArr[1];
            indices=sfbi[1].split('~');
            startIndex=indices[0];
            endIndex=indices[1];
            //startIndex=new RegExp('\\b' + commentStr + '\\b');
            //endIndex=startIndex+commentStr.length;

            if (!el) el = document.getElementById('essay_detail');
            if (!sel) sel = rangy.getSelection();
            if (!range) range = rangy.createRange();
            range.selectCharacters(el, startIndex, endIndex);
            sel.setSingleRange(range);
            $scope.setHilights(0,'',0);
        }    
        data.data.essay=$("#essay_detail").html();
    }else if(Object.keys(window.essaySpellingErrors).length&gt;0){
        for (var i = 0; i &lt; window.essaySpellingErrors.length; i++) {
            var spellWord=window.essaySpellingErrors[i];

            var regex = new RegExp('\\b' + spellWord + '\\b','gi');
            startIndex = $("#essay_detail").text().search(regex);
            //endIndex=essayPlainText.indexOf(spellWord);
            var results = new Array();//this is the results you want
            while (regex.exec($("#essay_detail").text())){
              results.push(regex.lastIndex);
            } 
            endIndex=startIndex+spellWord.length;
            var title='Comment for [' + spellWord + ']';
            var label=startIndex + '~' + endIndex;
            var commentText="Misspelt : "+spellWord;
            var commentIndex=$scope.comments.length;
            var commentObj=[title,label,commentText,commentIndex];
            $scope.createCommentBox(commentObj);
            if (!el) el = document.getElementById('essay_detail');
            if (!sel) sel = rangy.getSelection();
            if (!range) range = rangy.createRange();
            range.selectCharacters(el, startIndex, endIndex);
            sel.setSingleRange(range);
            $scope.setHilights(0, '',1);    
           // }

            //$scope.togglecomment = true; 
        }    
        data.data.essay=$("#essay_detail").html();
    }

 $scope.createCommentBox = function(commentObj){
    var commentObject = { 'comment' : {'commentFor' : commentObj[0] , 'commentRange' : commentObj[1] , 'commentText' : commentObj[2], 'commentIndex' : commentObj[3]}};
    $scope.comments.push(commentObject);
};
$scope.setHilights=function(n, evalNum , isSpellErrorComment) {
//console.log('set HiliteN');
    var commentText=""; 
    rSel = rangy.getSelection(); //console.log(rSel);
    var txt = rSel.toHtml().replace(/style="background-color:#ff0000"/g, 'class="commentHilight" name="' + parseInt(startIndex) + '~' + parseInt(endIndex) + '"');
    var textK = rSel.text();
    //console.log(rSel.toHtml()+'------'+txt+'--------'+textK);
    rRange = rSel.getRangeAt(0);
    rRange.deleteContents();
    var str='&lt;span class="commentHilight startIndex-'+ parseInt(startIndex) +' endIndex-'+parseInt(endIndex)+'" label="' + parseInt(startIndex) + '~' + parseInt(endIndex) + '"&gt;' + textK + '&lt;/span&gt;';
    var node = rRange.createContextualFragment(str);
    rRange.insertNode(node);
    rSel.removeAllRanges();
    return;
}
</code></pre>