Javascript子串多行替换为RegExp

时间:2010-12-26 10:45:20

标签: javascript regex

我在多行字符串中匹配正则表达式时遇到了一些麻烦。

<script>
var str="Welcome to Google!\n";
str = str + "We are proud to announce that Microsoft has \n";
str = str + "one of the worst Web Developers sites in the world.";

document.write(str.replace(/.*(microsoft).*/gmi, "$1"));
</script>

http://jsbin.com/osoli3/3/edit

正如您在上面的链接中看到的那样,代码的输出如下所示:

Welcome to Google! Microsoft one of the worst Web Developers sites in the world.

这意味着,replace()方法逐行进行,如果该行中没有匹配项,则只返回整行... 即使它具有“m”(多行)修饰符< /强> ...

1 个答案:

答案 0 :(得分:2)

多行选项只会更改代码^$的工作方式,而不会改变代码.的工作方式。

使用匹配任何字符的模式,使用[\w\W]而不是.这样的集合,因为它只匹配非换行字符。

document.write(str.replace(/[\w\W]*(microsoft)[\w\W]*/gmi, "$1"));