pepe
pepe

Reputation: 335

How to add into array the url that contains specific String?

I am trying to get all values of element

var request = require('request');
var cheerio = require('cheerio');
var url = "https://www.mismarcadores.com";
request(url, function(err, resp, body) {

    if (err) throw err;
    var $ = cheerio.load(body);
    var addUrl= [];
    $('a').each(function (i, element) {
        var a = $(this);
        var href = a.attr('href');
        addUrl.push(href);      
    })
    console.log(array[0]);
})

I have this code that add the links to array called addUrl , this works perfect but now I am looking how to add to this array if the url contains the word 'baloncesto' in href.

Good example : https://www.mismarcadores.com/baloncesto/alemania/

This URL , is good but

Bad example : https://www.mismarcadores.com/golf/

This is wrong.

I am developing this using NodeJS but this is only a simply javascript that now I don't know how to made this.

Could anyone help to me?

Upvotes: 1

Views: 183

Answers (4)

Songgen
Songgen

Reputation: 57

Please try like this:

var request = require('request');
var cheerio = require('cheerio');
var url = "https://www.mismarcadores.com";
var filterStr = 'baloncesto';
request(url, function(err, resp, body) {

    if (err) throw err;
    var $ = cheerio.load(body);
    var addUrl= [];
    $('a').each(function (i, element) {
        var href = $(this).attr('href');
        if (href.includes(filterStr)) addUrl.push(href);
    })
    console.log(addUrl);
})

Upvotes: 1

ingernet
ingernet

Reputation: 1534

Okay, so what you're looking for is a pattern match - if href contains the string baloncesto. I suspect that this SO thread will be helpful to you - you're basically looking to nest this line -

addUrl.push(href);

- in an if statement, like

if(href.includes('baloncesto')) { addUrl.push(href); }

...but definitely look at that other answer for reference, in case you're using a version of JS that's older and not compatible with ES6.

Upvotes: 0

LSTM
LSTM

Reputation: 128

Try this

var request = require('request');
var cheerio = require('cheerio');
var url = "https://www.mismarcadores.com";
request(url, function(err, resp, body) {

if (err) throw err;
var $ = cheerio.load(body);
var addUrl= [];
$('a').each(function (i, element) {
    var a = $(this);
    var href = a.attr('href');
    if (decodeURIComponent(href).contains('baloncesto')){
        addUrl.push(href);    
    } else {
    //do something else
    }
})
console.log(array[0]);

})

Upvotes: 0

rakesh ROCKING
rakesh ROCKING

Reputation: 81

you can try this
if(href.contains('baloncesto')){
  addUrl.push(href);      
 }

Upvotes: 0

Related Questions