What is the most convenient way to convert HTML to plain text while preserving line breaks (with JavaScript)?

前端 未结 5 1959
长发绾君心
长发绾君心 2020-12-10 04:24

Basically I just need the effect of copying that HTML from browser window and pasting it in a textarea element.

For example I want this:

Som

5条回答
  •  北海茫月
    2020-12-10 04:39

    I made a function based on this answer: https://stackoverflow.com/a/42254787/3626940

    function htmlToText(html){
        //remove code brakes and tabs
        html = html.replace(/\n/g, "");
        html = html.replace(/\t/g, "");
    
        //keep html brakes and tabs
        html = html.replace(/<\/td>/g, "\t");
        html = html.replace(/<\/table>/g, "\n");
        html = html.replace(/<\/tr>/g, "\n");
        html = html.replace(/<\/p>/g, "\n");
        html = html.replace(/<\/div>/g, "\n");
        html = html.replace(/<\/h>/g, "\n");
        html = html.replace(/
    /g, "\n"); html = html.replace(//g, "\n"); //parse html into text var dom = (new DOMParser()).parseFromString('' + html, 'text/html'); return dom.body.textContent; }

提交回复
热议问题