复杂的html string.replace函数 [英] complex html string.replace function

查看:84
本文介绍了复杂的html string.replace函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的html,它是从这样的字符串的jSon数据库生成的:

I have very simple html that is generated from a jSon database of strings like this:

"<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是搜索术语。我想通过HTM1< i> searchterm< / i>将每个出现的searchterm包含在结果中。我正在为我所参与的每个标签使用这些正则表达式和函数,例如:

And a variable RESULTSshow that is a concatenation of such strings, an another var: searchterm that is the search term. I want to enclose each occurence of searchterm in the results by the HTMl <i>searchterm</i> I am using those regexp and function for each tags I am intereseted in, for example:

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,那不仅会改变标签内的文本但也要更改标签本身。

The problem is that if searchterm is "p", that will not only change the text inside the tags but also change the tag itself.

如何阻止它更改标签?我真的想用一个regExp来做,而不是为了速度而循环通过html(dom)。

How can I stop it from changing the tags ? I really want to do it with a regExp, not looping through html (dom) for speed sake.

推荐答案

现在使用这个精彩小RegExp而不是过于复杂的第一个:

Now using this wonderful little RegExp instead of the overly complicated first one:

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

这篇关于复杂的html string.replace函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆