Cheerio: No simple way to preserve new lines in text

Created on 8 Oct 2015  路  3Comments  路  Source: cheeriojs/cheerio

When you do

 $b.text($a.text());

you lose the new lines coming from <BR> elements.

This is consistent with what you have in jQuery but jQuery users have the option to use innerText which doesn't have the same problem (contrary to textContent).

Would a PR adding a new textln function be welcome or should cheerio users just monkey patch when they need to preserve new lines ?

Most helpful comment

You can write you own method. Like this:

$.prototype.textln = function () {
    this.find('br').replaceWith('\n');
    this.find('*').each(function () {
        $(this).replaceWith($(this).html());
    });
    return this.html();
}
$('a').textln();

All 3 comments

The goal of this project is parity with jQuery's DOM manipulation/traversal API, so I don't think a custom function is in-scope.

You can write you own method. Like this:

$.prototype.textln = function () {
    this.find('br').replaceWith('\n');
    this.find('*').each(function () {
        $(this).replaceWith($(this).html());
    });
    return this.html();
}
$('a').textln();

Thanks, @alanev!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

trevorfrese picture trevorfrese  路  4Comments

tndev picture tndev  路  4Comments

unicrus picture unicrus  路  4Comments

francoisromain picture francoisromain  路  5Comments

becush picture becush  路  3Comments