js realizes that no matter how many children there are in a rich text string, the specified character is replaced with another

Foreword:

        js realizes that no matter how many children there are in a rich text string, the specified character is replaced with another

Implementation steps:

Calling method:
this.nowHtmlT = this.replaceText(this.nowHtmlT,this.addBtnText,"${one}")
Packaging method:

    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;
    },

Guess you like

Origin blog.csdn.net/weixin_44727080/article/details/132092760