JavaScript regex multiline flag doesn't work

前端 未结 5 1669
清酒与你
清酒与你 2020-11-22 09:41

I wrote a regex to fetch string from HTML, but it seems the multiline flag doesn\'t work.

This is my pattern and I want to get the text in h1 tag.

5条回答
  •  感情败类
    2020-11-22 10:35

    You are looking for the /.../s modifier, also known as the dotall modifier. It forces the dot . to also match newlines, which it does not do by default.

    The bad news is that it does not exist in JavaScript (it does as of ES2018, see below). The good news is that you can work around it by using a character class (e.g. \s) and its negation (\S) together, like this:

    [\s\S]
    

    So in your case the regex would become:

    /
    [\s\S]*

    ([^<]+?)<\/h1>/i


    As of ES2018, JavaScript supports the s (dotAll) flag, so in a modern environment your regular expression could be as you wrote it, but with an s flag at the end (rather than m; m changes how ^ and $ work, not .):

    /
    .*

    ([^<]+?)<\/h1>/is

提交回复
热议问题