Source

dom/replaceTextsInHTMLStr.js

"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var getDOMTextNodesUnder_1 = __importDefault(require("./getDOMTextNodesUnder"));
// Init dom parser
var domparser = new DOMParser();
/**
 * Replace text in HTML string
 *
 * @param htmlStr
 * @category dom
 * @module replaceTextsInHTMLStr
 */
var replaceTextsInHTMLStr = function (htmlStr, replacer) {
    // Parse HTML string
    var doc = domparser.parseFromString(htmlStr, 'text/html');
    // Get all elements that containing a text node
    var textNodes = (0, getDOMTextNodesUnder_1.default)(doc.body);
    // Replace URLs in each text node
    textNodes.forEach(function (node) {
        // Get the parent element of this text node
        var parentEl = node.parentElement;
        if (parentEl) {
            // Get the html string of the parent element
            var nodeHTMLStr = parentEl.innerHTML;
            // Replace the urls in the innerHTML of its parent element.
            parentEl.innerHTML = replacer(nodeHTMLStr);
        }
    });
    // Return manipulated HTML string
    return doc.body.innerHTML;
};
exports.default = replaceTextsInHTMLStr;