Source

dom/replaceTextsInHTMLStr.js

  1. "use strict";
  2. var __importDefault = (this && this.__importDefault) || function (mod) {
  3. return (mod && mod.__esModule) ? mod : { "default": mod };
  4. };
  5. Object.defineProperty(exports, "__esModule", { value: true });
  6. var getDOMTextNodesUnder_1 = __importDefault(require("./getDOMTextNodesUnder"));
  7. // Init dom parser
  8. var domparser = new DOMParser();
  9. /**
  10. * Replace text in HTML string
  11. *
  12. * @param htmlStr
  13. * @category dom
  14. * @module replaceTextsInHTMLStr
  15. */
  16. var replaceTextsInHTMLStr = function (htmlStr, replacer) {
  17. // Parse HTML string
  18. var doc = domparser.parseFromString(htmlStr, 'text/html');
  19. // Get all elements that containing a text node
  20. var textNodes = (0, getDOMTextNodesUnder_1.default)(doc.body);
  21. // Replace URLs in each text node
  22. textNodes.forEach(function (node) {
  23. // Get the parent element of this text node
  24. var parentEl = node.parentElement;
  25. if (parentEl) {
  26. // Get the html string of the parent element
  27. var nodeHTMLStr = parentEl.innerHTML;
  28. // Replace the urls in the innerHTML of its parent element.
  29. parentEl.innerHTML = replacer(nodeHTMLStr);
  30. }
  31. });
  32. // Return manipulated HTML string
  33. return doc.body.innerHTML;
  34. };
  35. exports.default = replaceTextsInHTMLStr;