Get multiple elements from node request and then choose one

My request gets multiple a tags from a page, and do some string manipulation on them. My problem is choosing just one string. My output is

string 1
string 2
string 3
etc...

I just want for instance

string 2

And when I do something like console.log(a[2]) , I'll get the second 't' in 'http'

How can I do this with the following code on my request

request(url, function (error, response, html) {
  if (!error && response.statusCode == 200) {
    var $ = cheerio.load(html);
    //parse to find cards
    $('div.card').each(function(i, element){
      //find all links
      a = ($(this).find('a').attr('href'));
      a = a.split('/')[3];
      //construct new string
      visiting = "http://api.website.com/stuff/"+a
      console.log(a);
      });
    };
  });

1 answer

  • answered 2018-09-17 07:30 Kariem Soudy


    try this,
    as i understand you need to add all tags in an array and then you can get elements by index

        request(url, function (error, response, html) {
          if (!error && response.statusCode == 200) {
                var $ = cheerio.load(html);
                //parse to find cards
                var a=[];
                $('div.card').each(function(i, element){
                      tag = $(this).find('a').attr('href').split('/')[3]
                      //construct new string
                      visiting = "http://api.website.com/stuff/"+tag
                      a.push(tag);
                  });
                console.log(a[2]);
            };
          });
    

    //edit 1

    you can use this function

        function getRandomInt(max) {
          return Math.floor(Math.random() * Math.floor(max));
        }
    

    in you code as follows:

        request(url, function (error, response, html) {
          if (!error && response.statusCode == 200) {
                var $ = cheerio.load(html);
                //parse to find cards
                var a=[];
                $('div.card').each(function(i, element){
                      tag = $(this).find('a').attr('href').split('/')[3]
                      //construct new string
                      visiting = "http://api.website.com/stuff/"+tag
                      a.push(tag);
                  });
                //get random tag
                console.log(a[getRandomInt(a.length)]);
            };
          });