首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将正则表达式仅限于非html文本

将正则表达式仅限于非html文本
EN

Stack Overflow用户
提问于 2018-07-24 05:07:34
回答 1查看 44关注 0票数 -1

我找到了这个javascript函数,它替换了字符串中的所有匹配项。它工作得很好,但我需要它只适用于非html元素,这只是意味着字符串中不在"<“和">”之间的任何部分。

String.prototype.replaceAll = function (strReplace, strWith) {
    // See http://stackoverflow.com/a/3561711/556609
    var esc = strReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    var reg = new RegExp(esc, 'ig');
    return this.replace(reg, strWith);
};

我希望这是因为"strReplace“字符串有时会出现在html中,因此会弄乱HTML输出。如有任何帮助,我们将非常感谢:)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-24 05:49:10

假设你想用replaceAll方法替换一个字符串:

  1. 如果一个字符串不是一个有效的html,则将其视为纯文本。
  2. 如果一个字符串是一个有效的html,则循环每个textContent以应用html

解决方案(使用element.innerHTML而不是正则表达式,正如@epascarello所说,使用正则表达式匹配html不是一个好主意):

使用.innerHTML

  • loop
  1. 将目标字符串加载到一个dom元素中,以获取所有文本节点。
  2. 对文本dom的内容应用replaceAll

String.prototype.replaceAll = function (strReplace, strWith) {
    // See http://stackoverflow.com/a/3561711/556609
    var esc = strReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
    var reg = new RegExp(esc, 'ig');
    return this.replace(reg, strWith);
}

function replaceAll2 (targetString, keyword, replaceWord) {
  if (!keyword) return targetString
  let el = document.createElement('div')
  el.style.display='none'
  el.innerHTML = targetString
  let walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false)
  let next = walk.nextNode()
  while (next) {
    next.textContent = next.textContent.replaceAll(keyword, replaceWord)
    next = walk.nextNode()
  }
  return el.innerHTML
}

let test1 = 'I am a plain text'
let test2 = 'I <span>am</span> a <p>plain</p> text'
console.log(replaceAll2(test1, 'pl', '1'))
console.log(replaceAll2(test2, 'pl', '2'))

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51487256

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档