簡體   English   中英

復雜的html string.replace函數

[英]complex html string.replace function

我有一個非常簡單的html,它是從jSon數據庫的字符串生成的,如下所示:

"<div style=\"padding-top:59px;\"><a href=\"http://www.macm.org/en/index.html\"><img src=\"http://www.artimap.com/montreal/www.macm.org.jpg\"><br>www.macm.org/en/index.html</a><h1>Musée d'art contemporain de Montréal</h1><p></p><p>A major Canadian institution dedicated exclusively to contemporary art, the Musée offers a varied program ranging from presentations of its Permanent Collection to exhibitions of works by Québec, Canadian and international artists. The Permanent Collection comprises some 7,000 works, including the largest collection of art by Paul-Émile Borduas.</p><div><p>185, Sainte-Catherine West (corner Jeanne-Mance)</p><p>H2X 3X5</p></div><b>514 847-6226</b></div>"

變量RESULTSshow是此類字符串的串聯,另一個var:searchterm是搜索項。 我想用HTMl <i> searchterm </ i>將結果中出現的每一個searchterm括起來,例如,我對插入的每個標簽都使用了這些正則表達式和正則表達式,例如:

var REG=new RegExp(searchterm,'gmi');
var regFUN=function(x){return x.replace(REG,"<i>$&</i>");};
var reg = new RegExp('<p>(.*?)</p>','gmi');
RESULTSshow=RESULTSshow.replace(reg,regFUN);
(I do this for every tags I am interested in highlighting) 
This does <i>"searchterm"</i> but also gives <<i>p</i>> if searchterm==="p" wich really bugs me for the two last days.

問題是,如果searchterm為“ p”,則不僅會更改標簽內的文本,還會更改標簽本身。

如何阻止它更改標簽? 我真的很想用regExp來做到這一點,而不是為了速度而遍歷html(dom)。

現在,使用這個奇妙的RegExp代替過於復雜的第一個:

REG=new RegExp("(?![^<>]*>)("+searchterm+")","gi");
RESULTSshow=RESULTSshow.replace(REG,'<i>$1</i>');

好吧,考慮到您的HTML不包含諸如SCRIPT,CDATA,STYLE之類的塊,可以使用正則表達式使用lookahead:

text = text.replace(/(?![^<>]*>)old/g, 'new');

盡管我會使用燈光解析器或自家的解析器,而不用擔心速度以獲得更好的支持。 請注意,如果您的屬性可能包含<>字符,則需要處理源。

嘗試這個 :

<html>
<head>
<script>
function t() {
    text = "<html><head></head><body><p>SuperDuck</p><p>Jumps over the lazy dog</p></body></html>";
    a = text.replace(/(?![^<>]*>)(p)/g, '<i>$1</i>');
    alert (a);
}
</script>
</head>
<body>
    <button onclick="t();">hit me!</button>
</body>
</html>

只需替換替換字符串中的(p) ,就可以跳過=)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM