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?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.