如何在带括号的子串匹配上应用正则表达式?

时间:2012-02-28 17:20:00

标签: javascript regex

我有一个HTML内容,我这样做是为了获取文本内容。

string='<img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img><img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img><img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img><img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img>'
re=(/([<][^<]+>)([^<]+)([<][^<]+>)/g);
newstr=string.replace(re,"$1$2$3");

这给了我原来的字符串。

我的问题是我需要在string.replace(regex,$2))之前应用另一个newstr=string.replace(re,"$1$2$3"

也就是说,在应用最终解决方案之前,我需要在参数化catch上应用另一个正则表达式。

1 个答案:

答案 0 :(得分:4)

不确定你在这里做什么,但我猜你正在寻找replace回调:

string='<img src="Randomz" alt="Randomz Image">Randomz is the name of the image</img><img src="Random'
re=(/([<][^<]+>)([^<]+)([<][^<]+>)/g);
newstr=string.replace(re, function($0, $1, $2, $3) {
     $2 = do_something_with($2);
     return $1 + $2 + $3;
});

作为旁注,正则表达式不是html转换的最佳工具。