html字符串转义与反转义

html字符串转义与反转义

html字符串转义

  • 方法一
    const htmlStr = `
`
; const escapeHtml = function (str) { if (Object.prototype.toString.call(str) !== '[object String]') { return ''; } return str.replace(/<|&|>/g, function (match) { return ({ '<': '<', '>': '>', '&': '&' })[match]; }); }; console.log(escapeHtml(htmlStr))
  • 方法二
    const htmlStr = `
`
; const escapeHtml = function (str) { let textNode = document.createTextNode(str); let div = document.createElement('div'); div.append(textNode); return div.innerHTML; }; console.log(escapeHtml(htmlStr))

html字符串反转义

    const htmlStr = `<div id="root" class="root">
    <div class="cls-1">
        <ul>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </div>
    <div class="cls-2">
        <ol>
            <li></li>
            <li></li>
            <li></li>
        </ol>
    </div>
    <div class="cls-3">
        <div class="cls-3-1"></div>
        <div class="cls-3-2"></div>
        <div class="cls-3-3"></div>
    </div>
</div>`;

    const unescapeHtml = function (str) {
        if (Object.prototype.toString.call(str) !== '[object String]') {
            return '';
        }
        return str.replace(/<|>|&/g, function (match) {
            return ({
                '<': '<',
                '>': '>',
                '&': '&'
            })[match];
        });
    };
    console.log(unescapeHtml(htmlStr))

你可能感兴趣的:(前端,javascript,html,javascript,elementui)