想要的效果
输入: let str ="<div><span>tests</span></div>"
输出 : {
tag: 'div',
children: [
{
tag: 'span'
},
],
}
实现
// 设置每个节点标签属性
// let attrRE = /\s([^'"/\s><]+?)[\s/>]|([^\s=]+)=\s?(".*?"|'.*?')/g;
function parseTag(tag) {
let res = {
type: "tag",
name: "",
voidElement: false,
attrs: {},
children: [],
};
let tagMatch = tag.match(/<\/?([^\s]+?)[/\s>]/);
if (tagMatch) {
// 标签名称为正则匹配的第2项
res.name = tagMatch[1];
if (tag.charAt(tag.length - 2) === "/") {
// 判断tag字符串倒数第二项是不是 / 设置为空标签。 例子:<img/>
res.voidElement = true;
}
}
// 匹配所有的标签正则
let classList = tag.match(/\s([^'"/\s><]+?)\s*?=\s*?(".*?"|'.*?')/g);
if (classList && classList.length) {
for (let i = 0; i < classList.length; i++) {
// 去空格再以= 分隔字符串 得到['属性名称','属性值']
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
function promiseForEach(arr, cb) {
let realResult = []
let result = Promise.resolve()
arr.forEach((a, index) => {
result = result.then(() => {
if (typeof cb === "function") {
return cb(a).then((res) => {
realResult.push(res)
})
}
})
})
return result.then(() => {
return realResult
})
}
promiseForEach(arr, (ele) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log(ele)
return resolve(ele)
}, Math.random() * 1000)
})
}).then((data) => {
console.log("成功")
console.log(data)
}).catch((err) => {
console.log("失败")
console.log(err)
})
/**
* 复制文本
* @param text
*/
export function copyText(text) {
const input = document.createElement("input")
input.value = text
document.body.appendChild(input)
input.select()
document.execCommand("Copy")
window.setTimeout(function () {
document.body.removeChild(input)
}, 0)
}
/**
* esc监听全屏
*/
export const listenfullscreen = (callback) => {
function listen() {
callback()
}
document.addEventListener("fullscreenchange", function () {
listen()
})
document.addEventListener("mozfullscreenchange", function () {
listen()
})
document.addEventListener("webkitfullscreenchange", function () {
listen()
})
document.addEventListener("msfullscreenchange", function () {
listen()
})
}
/**
* 浏览器判断是否全屏
*/
export const fullscreenEnable = () => {
return document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
}
/**
* 浏览器全屏
*/
export const re
Number.prototype.toFixed = function (n) {
if (n != undefined && (isNaN(n) || Number(n) > 17 || Number(n) < 0)) {
throw new Error("输入正确的精度范围");
}
// 拆分小数点整数和小数
var num = this;
var f = '';
if (Number(num) < 0) {
num = -Number(num);
f = '-';
}
var numList = num.toString().split(".");
// 整数
var iN = numList[0];
// 小数
var dN = numList[1];
n = parseInt(n);
if (isNaN(n) || Number(n) === 0) {
// 0或者不填的时候,按0来处理
if(dN === undefined){
return num + '';
}
var idN = Number(dN.toString().substr(0, 1));
if (idN >= 5) {
if (Number(iN) < 0) {
iN = Number(iN) - 1
} else {
iN = Number(iN) + 1
}
}
return iN + '';
} else {
var dNL = dN === undefined ? 0 : dN.length;
if (dNL < n) {
// 如果小数位不够的话,那就补全
var oldN = num.toString().ind