UNPKG

jslib-tools

Version:

js工具库 封装常用的工具函数 如深拷贝 时间转换日期格式化、浏览器判断等,提高开发效率

47 lines (46 loc) 1.53 kB
/* * @Author: zhangyu * @Email: zhangdulin@outlook.com * @Date: 2021-06-08 11:30:40 * @LastEditors: zhangyu * @LastEditTime: 2021-06-17 10:02:48 * @Description: */ // var utf16toEntities = require("./.internal/utf16toEntities"); // var entitiestoUtf16 = require("./.internal/entitiestoUtf16"); import { utf16toEntities } from './.internal/utf16toEntities' import { entitiestoUtf16 } from './.internal/entitiestoUtf16' /** * @description 处理文本,客户端无法识别h5的br标签和空格符,因此需要处理br标签为\n和空格符为 '' * @param {string} str 需要编译/转义的字符串 * @param {string} type encode 编译 decode 转义 * @returns {string} 编译/转义后的字符串 * @example * handleText("<br>&nbsp;&lt;&gt;", "encode") => "\n <>" * handleText("\n <>", "decode") => "<br>&nbsp;&lt;&gt;" */ export function handleText(str = "", type = "encode") { if (!str) return ""; if (typeof str !== "string") { console.error("handleText数据类型需要是字符串类型"); return str; } /* eslint-disable no-unused-vars */ let newStr = null; if (type === "encode") { newStr = entitiestoUtf16(str) .replace(/<br>/gi, "\n") .replace(/&nbsp;/g, " ") .replace("&lt;", "<") .replace("&gt;", ">"); } else if (type === "decode") { newStr = utf16toEntities(str) .replace("<", "&lt;") .replace(">", "&gt;") .replace(/\n|\r\n/g, "<br>") .replace(/[ ]/g, "&nbsp;"); } else { return str; } return newStr; }