一·、发布包创建
我们先创建一个文件夹命名为:itheima-tools
在文件夹创三个文件,分别为:index.js、package.json、README.md
准备工作,我们早package.json 中写:
{
"name": "itheima-tools",
"version": "1.0.0",
"main": "index.js",
"description": "提供了格式化时间、HTMLEscape功能",
"keywords": [
"itheima",
"dataFormat",
"escape"
],
"license": "ISC"
}
二、格式化时间main 属性
我们在index.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
}
我们再创建一个命名为:01.test.js的文件接收一下
const itheima = require('./index')
const dtStr = itheima.dateFormat(new Date())
console.log(dtStr);
运行结果:
可以发现我们实现了时间的格式化
三、转义HTML格式
我们创建这样的代码:
// 转义html字符
function htmlEscape(htmlStr) {
return htmlStr.replace(/<|>|"|&/g, (match) => {
switch (match) {
case '<':
return '<'
case '>':
return '>'
case '"':
return '"'
case '&':
return '&'
}
})
}
// 向外暴露
module.exports = {
htmlEscape
}
在测试文件中写这样的代码接收:
const itheima = require('./index')
const htmlStr='<h1 title="123">这是一个标签<span>aaa </span></h1>'
const str=itheima.htmlEscape(htmlStr)
console.log(str);
结果: