找到innerText

时间:2016-02-01 15:10:41

标签: javascript html regex

我有一个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之间,标签已经包含了我得到的文本部分。

示例:

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

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

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

配置:javascript,以怪癖模式编译(仅在IE上使用,我不关心其他浏览器)。

1 个答案:

答案 0 :(得分:1)

  

我得到的麻烦是,如果已经有一个围绕motErreur的范围

假设你获得的innerHTML只能在你的mot errur周围有一个标签你可以检查是否有这样的跨度:

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将只有一个可能的孩子,并且这个孩子将包裹你的motErreur

相关问题