Search code examples
javascriptnode.jsreactjsckeditorckeditor5

How to convert html string into plain text in React?


How do I convert html string (with a lot of tags etc.) into plain text in React? Any npm module maybe?

I haven't found any methods for converting html string to plain text. I need this because I want to save a text file edited in Ckeditor 5 as a plain text file, but Ckeditor 5 manages data in html or markdown format.


Solution

  • You can write your own piece of code to make that happen, no library needed.

    var htmlString = "<h1><b>test</b></h1>";
    var plainString = htmlString.replace(/<[^>]+>/g, '');
    
    console.log(plainString ); // you will have your plain text
    

    or

    function getText(html){
        var divContainer= document.createElement("div");
        divContainer.innerHTML = html;
        return divContainer.textContent || divContainer.innerText || "";
    }
    
    var yourString= "<div><h1>Hello World</h1>\n<p>We are in SOF</p></div>";
    
    console.log(getText(yourString));