开发者

Javascript substrings multiline replace by RegExp

I'm having some troubles with matching a regular expression in multi-line string.

<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

As you may see on the link above, the output of the code looks like this:

Welcome to Goog开发者_如何学JAVAle! Microsoft one of the worst Web Developers sites in the world.

Which means, that the replace() method goes line by line and if there's no match in that line, it returns just the whole line... Even if it has the "m" (multiline) modifier...


The multiline option only changes how the codes ^ and $ work, not how the code . works.

Use a pattern where you match any character using a set like [\w\W] instead of ., as that only matches non-linebreak characters.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜