14

巧用DOM API实现HTML字符的转义和反转义

 3 years ago
source link: https://www.zhangxinxu.com/wordpress/2021/01/dom-api-html-encode-decode/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

byzhangxinxu from https://www.zhangxinxu.com/wordpress/?p=9770

本文欢迎分享与聚合,全文转载就不必了,尊重版权,圈子就这么大,若急用可以联系授权。

FJraqaz.png!mobile

一、HTML字符的转义

不转弯,HTML字符转义有更简单更容易记忆的方法,如下:

let textNode = document.createTextNode('<span>by zhangxinxu</span>');
let div = document.createElement('div');
div.append(textNode);
console.log(div.innerHTML);

也就是把HTML内容作为文本节点的textContent内容,然后使用普通元素的innerHTML属性返回下就可以了。

上面代码输出的结果是:

<span>by zhangxinxu</span>

大家可以复制上面代码在控制台跑一下,例如下图就是我在Chrome浏览器中运行的结果:

zIraAne.png!mobile

二、HTML字符的反转义

这个需要用到的DOM API就相对稀罕了一点,使用DOMParser API。

代码示意:

let str = '<span>by zhangxinxu</span>';
let doc = new DOMParser().parseFromString(str, 'text/html');
console.log(doc.documentElement.textContent);

结果就是:

<span>by zhangxinxu</span>

眼见为实,运行截图参见下方:

IJBNFbI.png!mobile

然后还有一种方法是借助 <textarea> 元素,这是IE浏览器时代常用的一种方法,代码示意如下:

let textarea = document.createElement('textarea');
textarea.innerHTML = '<span>by zhangxinxu</span>';
console.log(textarea.childNodes[0].nodeValue);

结果也是一样的,转义的HTML标签都反转义回来了:

MVB3EjY.png!mobile

//zxx: 如果你看到这段文字,说明你现在访问是体验糟糕的垃圾盗版网站,你可以访问原文获得很好的体验:https://www.zhangxinxu.com/wordpress/?p=9770(作者张鑫旭)

三、DOM API方法的缺点

DOM API方法利用了浏览器的能力,更容易上手,转义结果也更安全,但是有个不足,那就是只能在浏览器上下文环境中使用。例如,如果是Service Workers环境,或者是Node.js环境中,这个方法就不行了,只能使用传统的字符串处理方法了。

传统的字符串处理代码示意:

/**
 * 转义HTML标签的方法
 * @param  {String} str 需要转义的HTML字符串
 * @return {String}     转义后的字符串
 */
var funEncodeHTML = function (str) {
    if (typeof str == 'string') {
        return str.replace(/<|&|>/g, function (matches) {
            return ({
                '<': '<',
                '>': '>',
                '&': '&'
            })[matches];
        });
    }

    return '';
};
/**
 * 反转义HTML标签的方法
 * @param  {String} str 需要反转义的字符串
 * @return {String}     反转义后的字符串
 */
var funDecodeHTML = function (str) {
    if (typeof str == 'string') {
        return str.replace(/<|>|&/g, function (matches) {
            return ({
                '<': '<',
                '>': '>',
                '&': '&'
            })[matches];
        });
    }

    return '';
};

四、爽言爽语

最近一周在更换网站备案,目前已经备案好了,网站访问将会恢复正常,文章更新也会回到正常频率。

OK,这就是本文全部内容啦!

感谢大家支持,如果觉得相关知识还真有用,欢迎转发到朋友圈,如果是PC端访问,则左侧或下方应该可以看到微信图标按钮,点击、扫码分享,感谢感谢!

BnyAV3B.png!mobile

本文为原创文章,欢迎分享,勿全文转载,如果实在喜欢,可收藏,永不过期,且会及时更新知识点及修正错误,阅读体验也更好。

本文地址: https://www.zhangxinxu.com/wordpress/?p=9770

(本篇完)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK