正则表达式以避免替换html标记的一部分

Regular expression to avoid replace part of html tag

本文关键字:一部分 html 替换 正则表达式      更新时间:2023-09-26

例如,我有一个字符串<i class='highlight'>L</i>olopolo。我需要把字母l改成<i class='highlight'>l</i>。如何制作一个正则表达式来忽略标签和里面的所有内容?

试试这个:

var string = "<i class='highlight'>L</i>olopolo";
string = string.replace(/l(?![^>]+>)(?![^<]*<'/)/g, "<i class='highlight'>l</i>");
alert(string);

如果你想有任意文本,那么你可以使用下面的代码:

var text = "foo";
var re = new RegExp(text + '(?![^>]+>)(?![^<]*</)', 'g');
var string = "<i class='highlight'>foobar</i>foobarfoobar";
string = string.replace(re, "<i class='highlight'>" + text + "</i>");
alert(string);

如前所述,使用正则表达式不是最好的主意,因此接下来最好的方法是在文本节点上循环并添加元素。

var charSplit = "l";
var elem = document.querySelector(".x");
var nodes = elem.childNodes;
for(var i=nodes.length-1;i>=0;i--){
   var node = nodes[i];
   if(node.nodeType === 3) {  //this is a text node
       var last = node;       
       var parts = node.nodeValue.split(charSplit);  //split of the character we are supposed to match
       node.nodeValue = parts[parts.length-1];  //set text node value to last index's value
       for (var j=parts.length-2; j>=0;j--){  //loop backwards ingnoring the last index since we already put that text in the textode
           var it = document.createElement("i");  //create the new element to add
           it.className="highligt";
           it.innerHTML = charSplit;
           node.parentNode.insertBefore(it,last);  //add it before the text node
           var tx = document.createTextNode(parts[j]);  //create new text node for text that becomes before the element
           node.parentNode.insertBefore(tx,it);  
           last = tx;
       }
   }
}
<p class="x"><i class='highlight'>L</i>olopolo</p>

我建议这样做,使用最少(也不那么复杂(的regex。如果您的字符串最初是html->的一部分,则可以获取父项,并更改textContent和innerHTML:

tag=document.getElementsByTagName('p')[0]; /*just as example,can be anything else*/
str=tag.textContent;
reg=/(l)/gi;
tag.innerHTML=str.replace(reg,"<i class='highlight'>"+'$1'+"</i>");

演示:http://jsfiddle.net/LzbkhLx7/

附言说明-textContent会给你"纯"字符串/文本,没有HTML标记-然后你可以很容易地包装l/l的每一个出现。

document.getElementsByClassName("highlight")[0].innerHTML = "l";

不需要正则表达式。

或者,如果您想将字母从大写更改为小写

var el = document.getElementsByClassName("highlight")[0];
el.innerHTML = el.innerHTML.toLowerCase();

当然,在执行此操作之前,您必须确保可以在innerHTML上调用toLowerCase(或其他方法(。