基于node.js的第三方模块(itheima-tools-djh)

此模块是基于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 "&lt;";
      case ">":
        return "&gt;";
      case '"':
        return "&quot;";
      case "&":
        return "&amp;";
    }
  });
}

// 定义还原 HTML 字符串的函数
function htmlUnEscape(str) {
  return str.replace(/&lt;|&gt;|&quot;|&amp;/g, (match) => {
    switch (match) {
      case "&lt;":
        return "<";
      case "&gt;":
        return ">";
      case "&quot;":
        return '"';
      case "&amp;":
        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&nbsp;</span></h1>';
// 调用 htmlEscape 方法进行转换
const str = itheima.htmlEscape(htmlstr);
// 转换的结果 &lt;h1 title=&quot;abc&quot;&gt;这是h1标签&lt;span&gt;123&amp;nbsp;&lt;/span&gt;&lt;/h1&gt;
console.log(str);
```

## 还原 HTML 中的特殊字符

```js
// 待还原的 HTML 字符串
const str2 = itheima.htmlUnEscape(str);
// 输出的结果 <h1 title="abc">这是h1标签<span>123&nbsp;</span></h1>
console.log(str2);
```

## 开源协议

ISC

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fusheng_cn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值