convertir texto a html in javascript

To convert text to HTML in JavaScript, you can use the createRange() and createContextualFragment() functions. Here's an example:

index.tsx
function convertToHTML(text) {
  const range = document.createRange();
  const fragment = range.createContextualFragment(text);
  return fragment;
}

const text = "This is some text.";
const html = convertToHTML(text);
console.log(html);
238 chars
10 lines

This will output a DocumentFragment object representing the converted HTML. You can then append this fragment to an element on the page using standard DOM manipulation techniques.

Note that this method does not escape any HTML entities, so you should only use it if you trust the source of the input text. If you need to convert text with entities (e.g. "<"), you can use the innerHTML property of an element instead:

index.tsx
function convertToHTML(text) {
  const el = document.createElement("div");
  el.innerHTML = text;
  return el;
}

const text = "This is some &lt;b&gt;bold&lt;/b&gt; text.";
const html = convertToHTML(text);
console.log(html.outerHTML);
236 chars
10 lines

This will output the HTML string:

<div>This is some <b>bold</b> text.</div>
42 chars
2 lines

related categories

gistlibby LogSnag