此模块是基于node.js开发,主要功能为格式化时间,转义、还原 HTML 字符串的函数。
npm地址:itheima-tools-djh - npm
模块的主要文件如下:
src文件夹中包含两个主要功能模块:
1. dateFormat.js 的功能为 格式化时间
// 定义格式化时间的函数
function dateFormat(dateStr) {
const dt = new Date(dateStr);
const y = dt.getFullYear();
const m = padZero(dt.getMonth() + 1);
const d = padZero(dt.getDate());
const hh = padZero(dt.getHours());
const mm = padZero(dt.getMinutes());
const ss = padZero(dt.getSeconds());
return `${y}-${m}-${d} ${hh}:${mm}:${ss}`;
}
// 定义一个补零的函数
function padZero(n) {
return n > 9 ? n : "0" + n;
}
module.exports = {
dateFormat,
};
2. htmlEscape.js 的功能为 转义、还原 HTML 字符串的函数
// 定义转义 HTML 字符的函数
function htmlEscape(htmlstr) {
return htmlstr.replace(/<|>|"|&/g, (match) => {
switch (match) {
case "<":
return "<";
case ">":
return ">";
case '"':
return """;
case "&":
return "&";
}
});
}
// 定义还原 HTML 字符串的函数
function htmlUnEscape(str) {
return str.replace(/<|>|"|&/g, (match) => {
switch (match) {
case "<":
return "<";
case ">":
return ">";
case """:
return '"';
case "&":
return "&";
}
});
}
module.exports = {
htmlEscape,
htmlUnEscape,
};
index.js文件
// 这是包的入口文件
const date = require("./src/dateFormat");
const escape = require("./src/htmlEscape");
// 向外暴露需要的成员
module.exports = {
...date,
...escape,
};
package.json
{
"name": "itheima-tools-djh",
"version": "1.0.0",
"main": "index.js",
"description": "提供了格式化时间、HTMLEscape相关的功能",
"keywords": [
"itheima",
"dateFormat",
"escape"
],
"license": "ISC"
}
README.md (文档使用说明)
## 安装
```
npm install itheima-tools-djh
```
## 导入
```js
const itheima = require("itheima-tools-djh");
```
## 格式化时间
```js
// 调用 dateFormat 对时间进行格式化
const dtStr = itheima.dateFormat(new Date());
// 结果 2022-07-16 21:13:13
console.log(dtStr);
```
## 转义 HTML 中的特殊字符
```js
// 待转换的 HTML 字符串
const htmlstr = '<h1 title="abc">这是h1标签<span>123 </span></h1>';
// 调用 htmlEscape 方法进行转换
const str = itheima.htmlEscape(htmlstr);
// 转换的结果 <h1 title="abc">这是h1标签<span>123&nbsp;</span></h1>
console.log(str);
```
## 还原 HTML 中的特殊字符
```js
// 待还原的 HTML 字符串
const str2 = itheima.htmlUnEscape(str);
// 输出的结果 <h1 title="abc">这是h1标签<span>123 </span></h1>
console.log(str2);
```
## 开源协议
ISC