Javascript正则表达式替换:无效的量词

时间:2012-10-21 21:16:04

标签: javascript regex

我无法在javascript中使用此正则表达式:

pat = new RegExp("Lorem(?=([^<]*($|<a|<[^/]|</[^a]))*($|(?<=a)))", "g");
test = test.replace(pat, '<a href="#">Lorem</a>');

我收到错误:invalid quantifier

但这里有效:http://gskinner.com/RegExr/?2va0g

感谢您的帮助:)

修改

我需要用链接替换每次出现的“String”,但前提是“String”不是链接。

居。

This is a <a href="#">String</a>. This is another String.

=&GT;

This is a <a href="#">String</a>. This is another <a href="#">String</a>.

如果还可以检查链接的URL:

,那就更好了
This is a <a href="http://www.test.com/String">link</a>

=&GT;

This is a <a href="http://www.test.com/String">link</a>

可能足以替换不在<a ... </a>内的所有字符串(第一个TAG没有故意关闭)

1 个答案:

答案 0 :(得分:0)

请参阅此示例Here

var toreplace = "String"; // Text to find
var rx = new RegExp ("((?!\/)" + toreplace + "(?!\"))(?!<(.*?)>)", "g");
var txt = "This is a <a href=\"#\">String</a>. This is another String."; // Text to replace.
var newtxt = txt.replace (rx, '<a href="#">$1</a>'); // New Text

结果是:

This is a <a href="#">String</a>. This is another String.

=&GT;

This is a <a href="#">String</a>. This is another <a href="#">String</a>.