Search code examples
javascriptnode.jscheerio

Refactor method chaining javascript


I call a function with bunch of nested method, i'm using web scraping tools called cheerio and i want to get the text out of it so i need to call a bunch of function. here's my example code.

        var text = $(el)
          .children()
          .first()
          .children()
          .first()
          .children()
          .first()
          .text()
          .replace(/\s\s+/g, " ");

My question is, how can i simplify my function so I have the same result without chaining my function?


Solution

  • A naive solution could be

    var text = $(">*:nth-child(1)".repeat(3), el).text().replace(/\s+/g, " ");
    

    For a good solution we'd need more context. Like what does the markup look like.