html-str-replace
Advanced tools
+93
-1
| // str: 目标字符串,sFrom: 被替换的字符串, sTo: 替换成字符串, | ||
| const htmlStrRep = function () { | ||
| this.endObj = { | ||
| tag: '', | ||
| children: [], | ||
| nextStr: null | ||
| } | ||
| this.originStr = '' | ||
| this.sFrom = '' | ||
| this.sTo = '' | ||
| } | ||
| htmlStrRep.prototype.startRep = function (str, sFrom, sTo = '') { | ||
| this.originStr = str | ||
| this.sFrom = sFrom | ||
| this.sTo = sTo | ||
| if (str.indexOf(sFrom) === -1 || !sFrom) { | ||
| return str | ||
| } | ||
| this.endObj = this.strToObj(str) | ||
| let changeStr = this.reGroup(this.endObj, sTo) | ||
| return changeStr | ||
| } | ||
| export default class htmlStrRep { | ||
| htmlStrRep.prototype.reGroup = function reGroup (splitObj, sTo) { | ||
| let groupStr = '' | ||
| if (splitObj.tag) { | ||
| let strArr = [] | ||
| // 递归组合 | ||
| splitObj.children.forEach((n) => { | ||
| strArr.push(this.reGroup(n, sTo)) | ||
| }) | ||
| groupStr += strArr.join(splitObj.tag) | ||
| } else { | ||
| // 在此替换 | ||
| groupStr += this.replace(splitObj.nextStr) | ||
| } | ||
| return groupStr | ||
| } | ||
| htmlStrRep.prototype.replace = function replace (str) { | ||
| return str.split(this.sFrom).join(this.sTo) | ||
| } | ||
| htmlStrRep.prototype.strToObj = function (str) { | ||
| // 暂存对象 | ||
| let cashObj = { | ||
| tag: '', | ||
| children: [], | ||
| nextStr: null | ||
| } | ||
| // 匹配tag并去重 | ||
| let tagArr = this.deleHave(this.machTag(str)) | ||
| if (tagArr) { | ||
| let tag = tagArr[0] | ||
| cashObj.tag = tag | ||
| cashObj.nextStr = '' | ||
| let childArr = str.split(tag) | ||
| childArr.forEach((s, j) => { | ||
| cashObj.children.push({ | ||
| tag: '', | ||
| children: [], | ||
| nextStr: childArr[j] | ||
| }) | ||
| if (s && this.deleHave(this.machTag(s))) { | ||
| cashObj.children[j] = this.strToObj(s) | ||
| } | ||
| }) | ||
| } else { | ||
| cashObj.nextStr = str | ||
| } | ||
| return cashObj | ||
| } | ||
| // 匹配标签 | ||
| htmlStrRep.prototype.machTag = function (str) { | ||
| return str.match(/<[^>]+>/g) | ||
| } | ||
| // 数组去重 | ||
| htmlStrRep.prototype.deleHave = function (arr) { | ||
| if (!arr) { | ||
| return arr | ||
| } | ||
| let darr = [] | ||
| for (let item of arr) { | ||
| if (darr.indexOf(item) === -1) { | ||
| darr.push(item) | ||
| } | ||
| } | ||
| return darr | ||
| } | ||
| export default htmlStrRep | ||
| class htmlStrRep2 { | ||
| constructor () { | ||
@@ -6,0 +98,0 @@ this.endObj = { |
+1
-1
| { | ||
| "name": "html-str-replace", | ||
| "version": "1.0.5", | ||
| "version": "1.0.6", | ||
| "description": "replace string for html", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
9526
25.28%281
44.1%