0

I have that:

<div contenteditable='true' class="my_div"> mango banana jus mango <b>orange<b/></div>

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ^1;;;;;;;;;;;;;;;;;;;;;;;;;;^18

I want to get the index of each mango.

I tried that:

$('.my_div').keyup(function(){
   let mots = $(".my_div").html().replace(/(<[^>]*>)|(&[^;]*;)/gi, ' ').split(' ');
   mots = mots.filter( function(val){return val !== ''} );
   var i;
   for (i = 0; i < mots.length; ++i) {
     if (mots[i] == "mango") {
       var indexOf_ = $(".my_div").html().indexOf(mots[i]);
       console.log(indexOf_);
     }
   }
});

But that code always give me '1' as index of 'mango'. It should give me 1 and 18 as index of mango

Where is my error ?

Thanks.

zagbala
  • 7
  • 3

2 Answers2

0

Please try this code -

$('.my_div').keyup(function(){

   var searchableString = $(".my_div").html();
   var keyword = "mango";

   var index = searchableString.indexOf(keyword);
   while (index >=0){
    console.log("Index : "+index);
    index = searchableString.indexOf(keyword, index+keyword.length)   ;
   }
 });
Omor Faruk
  • 36
  • 5
0

You always get 1 because you always start from the beginning of the string. The indexOf method accepts a second parameter (optional) called 'fromIndex' which indicates the index to start the search at. So in my method below, I keep track of the last index of mango found 'lastIndexOf' and start from there the next time.

$('.my_div').keyup(function(){
   let mots = $(".my_div").html().replace(/(<[^>]*>)|(&[^;]*;)/gi, ' ').split(' ');
   mots = mots.filter( function(val){return val !== ''} );
   var i;
   // Keep track of the last index
   var lastIndexOf = 0;
   for (i = 0; i < mots.length; ++i) {
     if (mots[i] == "mango") {
       // Start searching from last index +1
       lastIndexOf = $(".my_div").html().indexOf(mots[i], lastIndexOf+1);
       console.log(lastIndexOf);
     }
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable='true' class="my_div"> mango banana jus mango <b>orange<b/></div>
Stefan Koenen
  • 2,289
  • 2
  • 20
  • 32