Answers for "convert html to js string"

5

convert a string to html element in js

/**
 * Convert a template string into HTML DOM nodes
 * @param  {String} str The template string
 * @return {Node}       The template HTML
 */
var stringToHTML = function (str) {
	var parser = new DOMParser();
	var doc = parser.parseFromString(str, 'text/html');
	return doc.body;
};
Posted by: Guest on May-28-2020
4

js convert html to text

// To remove all HTML tags use the ".replace(/<[^>]+>/g, '')" method.
let myHTML= "<div><h1>Jimbo.</h1>\n<p>That's what she said</p></div>";
let strippedHtml = myHTML.replace(/<[^>]+>/g, '');
console.log(stripedHtml); // Jimbo. That's what she said
Posted by: Guest on September-06-2021
3

html to string

import { decode } from 'html-entities';

function htmlToString(returnText: string) {
  //-- remove BR tags and replace them with line break
  returnText = returnText.replace(/<br>/gi, "\n");
  returnText = returnText.replace(/<br\s\/>/gi, "\n");
  returnText = returnText.replace(/<br\/>/gi, "\n");

  // //-- remove P and A tags but preserve what's inside of them
  returnText = returnText.replace(/<p.*>/gi, "\n");
  returnText = returnText.replace(/<a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 ($1)");

  // //-- remove all inside SCRIPT and STYLE tags
  returnText = returnText.replace(/<script.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/script>/gi, "");
  returnText = returnText.replace(/<style.*>[\w\W]{1,}(.*?)[\w\W]{1,}<\/style>/gi, "");

  // //-- remove all else
  returnText = returnText.replace(/<(?:.|\s)*?>/g, "");

  // //-- get rid of more than 2 multiple line breaks:
  returnText = returnText.replace(/(?:(?:\r\n|\r|\n)\s*){2,}/gim, "\n\n");

  //-- get rid of more than 2 spaces:
  returnText = returnText.replace(/ +(?= )/g, '');

  returnText = returnText.replace(/<[^>]+>/g, '').replace(/&lt;/g, "<").replace(/&gt;/g, ">")
  returnText = decode(returnText);
  
  return returnText;
}
Posted by: Guest on February-11-2021

Code answers related to "convert html to js string"

Code answers related to "Javascript"

Browse Popular Code Answers by Language