简体   繁体   中英

html to plaintext with NodeJS on server side

on the server-side, using Nodejs. I receive a text message containing HTML. I want a function that converts the html to plain text. And please don't tell me to add the tag <plaintext> or <pre> . (convert_to_html function doesn't exist in nodejs)

socket.on('echo', (text) => {
   plaintext = convert_to_html(text);
   socket.emit('echo', {
      message: plaintext
   });
});

ideal results:

input: <h1>haha i am big</h1>

plaintext(what i want plaintext to be): &lt;h1 &60;haha i am big &lt;/h1 &60;

output: <h1>haha i am big</h1>

current result:

input: <h1>haha i am big</h1>

plaintext: <h1>haha i am big</h1>

output: haha i am big

You can use the insertAdjacementHTML method on the browser side, here you go an example

socket.on("response", function (msg) {
  const messages = document.getElementById("messages");
  messages.insertAdjacentHTML("beforebegin", msg);
  window.scrollTo(0, document.body.scrollHeight);
});

still don't have a proper solution. while i wait for one, i will use reserved characters as a temporary solution. https://devpractical.com/display-html-tags-as-plain-text/#:~:text=You%20can%20show%20HTML%20tags,the%20reader%20on%20the%20browser .

function parse_to_plain_text(html){
  var result = "";
  for (var i = 0; i < html.length; i++) {
    var current_char = html[i];
  
    if (current_char == ' '){
      result += "&nbsp;"
    }
    else if (current_char == '<'){
      result += "&lt;"
    }
    else if (current_char == '>'){
      result += "&gt;"
    }
    else if (current_char == '&'){
      result += "&amp;"
    }
    else if (current_char == '"'){
      result += "&quot;"
    }
    else if (current_char == "'"){
      result += "&apos;"
    }
    else{
      result += current_char;
    }
  }
  return result;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM