Link to home
Start Free TrialLog in
Avatar of Stephen Forlance
Stephen Forlance

asked on

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

Avatar of leakim971
leakim971
Flag of Guadeloupe image

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
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Stephen Forlance
Stephen Forlance

ASKER

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

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.