0
for(var x in urls){
    var response = UrlFetchApp.fetch(urls[x],urlFetchOptions);
    var code = response.getContentText();
    for(var y = 0; y < messagesToCheckFor.length; y++){
      var message = messagesToCheckFor[y];
      if(code.indexOf(message) !== -1){
        bad_urls.push(urls[x]);
        break;
      }
    }
  }`

This code in a Google Ads script checks through all URLs for a piece of HTML, and if found, pushes that URL to an array (bad_urls). However I'd like to amend it so that it instead counts the number of occurrences of the piece of HTML and then adds each URL and the total count to an array so that I can record their values in a google sheet

I think I need something like the below to use regex to count successive matches but I'm not sure how to add the count to a variable and then push both url and count to their own array. Thanks

var re = /dpb-product-link svelte-1yex87k/g;
var outofStockMatch = [];
count = 0;
        while (re.exec(code)) {
          outofStockMatch = ++count;

zjcannon
  • 1
  • 1
  • And, just in case, see my answer about Cheerio, probably it makes sense to parse the html this way instead: https://stackoverflow.com/a/69351275/14265469 – Yuri Khristich Sep 28 '21 at 15:13

1 Answers1

0

Not sure if I understand your goal right. Probably you need something like this (to count substrings in given text):

var text = 'a b c d a a e f';

function count(text, find) {
  try { return text.match(RegExp(find, 'g')).length }
  catch(e) {return 0}
}

console.log(count(text, 'a')); // output: 3
console.log(count(text, 'b')); // output: 1
console.log(count(text, 'z')); // output: 0
Yuri Khristich
  • 13,448
  • 2
  • 8
  • 23
  • I am trying to count the number of occurrences of a piece of text within a webpage and assign the value to a variable – zjcannon Sep 28 '21 at 14:31
  • for(var x in urls){ var response = UrlFetchApp.fetch(urls[x],urlFetchOptions); var code = response.getContentText(); count = (code.match(/dpb-unavailable svelte-1yex87k/g) || []).length; for(var y = 0; y < messagesToCheckFor.length; y++){ var message = messagesToCheckFor[y]; if(code.indexOf(message) !== -1){ bad_urls.push(urls[x]); break; } } } – zjcannon Sep 28 '21 at 14:35
  • My function `count()` does exactly this: gives the number of given strings inside of given text. Try it this way: `var c = count(piece_of_text, html_code)`. `c` will be number of `piece_of_text`s inside of `html_code` – Yuri Khristich Sep 28 '21 at 15:08
  • Okay but this is running in google ads scripts so count is not a function that can be used – zjcannon Sep 28 '21 at 16:58
  • Sorry, I think you need to make your code reproducible (executable by 'Run code snippet' button) and then I (or someone) will able to show you how it could works. – Yuri Khristich Sep 28 '21 at 17:03