How to remove certain empty new lines/blank spaces

So I'm learning web scraping on my test store and I'm not sure how to properly remove empty new lines from the 'sizes' array.

 const $ = cheerio.load(body)

            $('div.listing').each((i, listing) => {

                let sizes = []

                let productUrl = $(listing).find('a').attr('href')
                let productTitle = $(listing).find('a').attr('title').toUpperCase()
                let productSizes = $(listing).find('.size-cont').text()

                if (products.indexOf(productUrl) == -1) {

                    sizes.push(productSizes)
                    console.log(sizes.join('').replace(/[^\S\r\n]+/g,"").trim()) // issue here

                }

            })

Current output:

9.0




9.5




10.0




10.5

I want it to be:

9.0
9.5
10.0
10.5

2 answers

  • answered 2019-11-08 13:37 Jose Barranco

    Try the following

    const output = sizes.join('').replace(/[^\S\r\n]+/g,"").trim();
    const noWhitespaceOutput.replace(" ", "");
    console.log(noWhitespaceOutput);
    

  • answered 2019-11-08 13:43 mplungjan

    You meant this?

    console.log(
    `9.0
    
    
    
    
    9.5
    
    
    
    
    10.0
    
    
    
    
    10.5`
    .replace(/(\s)+/g,"$1")
    )