JS count number of replacements

I have this snipped of jquery/js and Im trying to count how many times the search string is replaced, but number seems to stay at 0.

Any ideas?

    var number=0;
    var text = sentences.innerHTML;
    var regex = new RegExp('('+$(this).text()+')', 'ig',function() {
    return ++number;
});

    text = text.replace(regex, '<span class="highlight" style="background:'+rand+';">$1</span>');
    sentences.innerHTML = text;
  alert(number);

Open in new window

Stephen ForlanceAsked:
Who is Participating?
 
Julian HansenCommented:
 var regex = new RegExp('('+$(this).text()+')', 'ig',function() {
    return ++number;
});

Open in new window

What reference are you using where RegExp takes 3 parameters - I was under the impression RegExp only takes two parameters - the expression and flags

I think you are confusing this with the replace() callback.

The replace function takes a callback that is called for each match - in it you construct and return the replacement string - this is where you do your count.
Like this
<script>
$(function() {
  var number=0;
  // GET THE SOURCE
  var sentences=$('#target')[0];
  var text = sentences.innerHTML;
  
  // CREATE THE RegExp
  var regex = new RegExp('(searchString)', 'ig');
  var color = ['red','green','blue'];
  // RUN THE REPLACE WITH A CALLBACK 
  // WE ONLY HAVE 1 PARENTHESES EXPRESSION SO ONLY p1 
  // (IF WE HAD MORE ( ) TERMS P2, P3 ... PN
  var text = text.replace(regex, function(match, p1, offset, string) {
    // COUNT THE MATCH
    number++;
    
    // SIMULATE RANDOM BACKGROUND COLOR
    var rand = color[number];
    
    // RETURN THE REPLACEMENT STRING
    return '<span class="highlight" style="background:'+rand+';">' + p1 + '</span>';
  });
  
  // SAVE IT BACK TO THE DOM
  sentences.innerHTML = text;
  
  // HOW MANY DID WE FIND
  alert(number);
});
</script>

Open in new window


Working sample here
0
 
leakim971PluritechnicianCommented:
your block line 1 to 5 doesn't finish to run before your browser javascript interpreter run line 7
this is the concept of asynchronous and synchronous function

you must run line 7 once you sure your block <1 to 5 is ended; not before
you may use promise

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Opérateurs/await
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/async_function
0
 
Stephen ForlanceAuthor Commented:
Hi Julian,

Here is the complete bit of code I'm using, I already has a loop in there for each keyword. I tried putting your matching part in but it comes up with matching 0

<ul id="keywords">
    <li>Hello</li> 
    <li>blah</li>
    <li>You</li>
</ul>

<div id="sentences">
								blah blah blah hello how are you?
					</div>

var keywords = document.querySelector('#keywords');
var back = ["#FFFF00","#FF69B4","#7FFF00"];
var loop=0;


$( document ).ready(function() {
$("#keywords li").each(function() {
 
     $(this).css('background-color',back[loop]);
  var rand = back[Math.floor(Math.random() * back.length)];
  var sentences = document.querySelector('#sentences');

    //var text = sentences.textContent;
    var number=0;
    var text = sentences.innerHTML;
    var regex = new RegExp('('+$(this).text()+')', 'ig',function() {
    return ++number;
});

    text = text.replace(regex, '<span class="highlight" style="background:'+back[loop]+';">$1</span>');
    sentences.innerHTML = text;
 ++loop;
  
});
});

Open in new window

0
 
Julian HansenCommented:
Where is my code in that listing?
Look at 26 to 28 - that is what you had originally. If you read my post I explained you can't put the callback on the RegEx - it must go on the replace.

I haven't got time to integrate right now - give it a go - and see how you get on. If it errors out - post your updated code and I will take a look when I am back in the office.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.