其实这篇文章已经发过一次了,但是已经数据丢失,莫得办法,只好重头再来,问题不大,就当时复习吧。
这个需求是在折腾WordPress编辑器从文本模式转到可视化模式。特殊字符会有不兼容的情况,所以需要做转义处理。
那么在JavaScript里怎么对HTML实体字符进行转义与反转义处理呢?
具体代码如下:
/**
* 实体字符编码
* @param {*} text 待编码的文本
* @returns
*/
function entitiesEncode(text) {
text = text.replace(/&/g, "&");
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
text = text.replace(/ /g, " ");
text = text.replace(/"/g, """);
return text;
}
/**
* 实体字符解码
* @param {*} text 待解码的文本
* @returns
*/
function entitiesDecode(text) {
text = text.replace(/&/g, "&");
text = text.replace(/</g, "<");
text = text.replace(/>/g, ">");
text = text.replace(/ /g, " ");
text = text.replace(/"/g, "'");
return text;
}