javascript - 找到innerText后获取innerHTML

标签 javascript html regex

我有一个正则表达式来查找我想要的文本部分:

var re = RegExp("(?:^\\W*|(" + motBefore.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ")\\W+)" + motErreur.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "(?:\\W+(" + motAfter.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ")|\\W*$)", "g"); 
var resultMatch = document.getElementById('edth_corps').innerText.match(re);

这样我就可以检索出需要用标点符号修改的文本部分。我从这里遇到的麻烦是检索它的innerHtml,这样我就可以知道在这部分中是否有“motErreur”周围的标签。

我需要使用innerHTML,因为我的函数的目的是在 motErreur 周围包裹一个跨度,但这:

var reInner = resultMatch[0].replace(new RegExp("\\b" + motErreur + "\\b", "gi"), '<span id="'+nbId+'" class="erreurOrthographe" oncontextmenu="rightClickMustWork(event, this);return false">' + motErreur + '</span>');
document.getElementById('edth_corps').innerHTML = document.getElementById('edth_corps').innerHTML.replace(resultMatch, reInner);

不起作用,因为在innerText和innerHTML之间,标签可能已经包裹住我得到的文本部分。

示例:

  • 输入 => this, tset, that ;结果:工作正常,因为innerHTML和innerText是相同的(没有标签会搞乱搜索)

  • 输入2 => this, <em>tset</em>, that ; result :不起作用,因为innerText和innerHTML不相同(resultMatch与上次替换中的变量不同)。

我实际上不知道如何以最简单的方式正确链接这两件事。

配置:javascript,以怪异模式编译(仅适用于 IE,我不关心其他浏览器)。

最佳答案

The trouble I get is that if there is already a span around motErreur

假设您获得的innerHTML只能在您的mot erreur周围有一个标签,您可以通过这种方式检查是否有跨度:

if (theInnerHtml.firstChild) {
    // It has at least one

    var yourSpan = document.createElement('span');

    // you set the innerHTML of yourSpan with the innerHTML of the child
    // Ex <p> blablabla <em>motErreur</em> blabla </p>
    // yourSpan will be "<span>motErreur</span>"
    yourSpan.innerHTML = theInnerHtml.firstChild.innerHTML;

    // you empty the innerHTML of your the child
    // It will be <p> blablabla <em></em> blabla </p>
    theInnerHTML.firstChil.innerHTML = "";

    // Then you append your span to the firstChild
    // It will be <p> blablabla <em><span>motErreur</span></em> blabla </p>
    theInnerHTML.firstChild.appendChild(yourSpan):

}

因此这意味着您的innerHTML将只有1个可能的子级,并且该子级将包装您的motErreur

关于javascript - 找到innerText后获取innerHTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35133902/

相关文章:

html - CSS 属性不可用

正则表达式在 C 中不起作用

c# - 为什么这个没有特殊字符的正则表达式匹配更长的字符串?

c# - 用于精确匹配 N 数的正则表达式

javascript - HTML 表格在 TD 之间移动鼠标时触发 mouseOut

Javascript slick.js 轮播向后拖动多个幻灯片超过第一个元素不起作用

html - 如何锚定到 HTML 详细信息中的目标元素

javascript - 如何从字符串中去除具有属性的 HTML 标签?

javascript - Jquery 可拖动碰撞检测错误

javascript - 实现 Jaspersoft Studio Community (v6.2.2) 显示 Highcharts 图表的自定义可视化组件