前言:
js实现富文本字符串中不管有几个子级,把指定的字符替换另一个
实现步骤:
调用方法:
this.nowHtmlT = this.replaceText(this.nowHtmlT,this.addBtnText,"${one}")
封装方法:
replaceText(text, oldStr, newStr) {// 检查是否为字符串类型if (typeof text !== 'string') {text = String(text);}// 替换字符text = text.replace(new RegExp(oldStr, "g"), newStr);// 处理子级if (text.includes('<') && text.includes('>')) {const start = text.indexOf('<');const end = text.indexOf('>') + 1;let subtext = text.substring(start, end);while (start >= 0 && end >= 0 && end > start) {const subtextNew = replaceText(subtext, oldStr, newStr);text = text.substring(0, start) + subtextNew + text.substring(end);subtext = text.substring(start, end);}}return text;},