0

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 Google! 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...

1 Answer 1

2

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"));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.