要从字符串创建正则表达式,必须使用Javascript的
RegExpobject。
如果你也想匹配/替换超过一次,那么你就 必须添加的
g(全局匹配)标志。这是一个例子:
var stringToGoIntoTheRegex = "abc";var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");// at this point, the line above is the same as: var regex = /#abc#/g;var input = "Hello this is #abc# some #abc# stuff.";var output = input.replace(regex, "!!");alert(output); // Hello this is !! some !! stuff.在一般情况下,在用作正则表达式前先对字符串进行转义:
但是,并非每个字符串都是有效的正则表达式:有些特殊字符,例如
(或
[。要变通解决此问题,只需将字符串转为正则表达式之前先对其进行转义。下面的示例中包含一个实用程序功能:
function escapeRegExp(stringToGoIntoTheRegex) { return stringToGoIntoTheRegex.replace(/[-/\^$*+?.()|[]{}]/g, '\$&');}var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from abovevar regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");// at this point, the line above is the same as: var regex = /#abc#/g;var input = "Hello this is #abc# some #abc# stuff.";var output = input.replace(regex, "!!");alert(output); // Hello this is !! some !! stuff.注意:问题中的正则表达式使用
s修饰符,该修饰符在提问时并不存在 ,但今天确实存在 -Javascript中 的
s( dotall)标志/修饰符。



