简体   繁体   中英

How to make javascript regular expression match any char and carriage return?

I have a html file like below.

  <body>  
    <p>Enter your phone number with area code and then click 
        Check The expected format is like</p>
    <form action="#">  
      <input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button>
    </form>  
  </body>  
</html>

I use below script which can print right result.

fs.readFile('test.html', 'utf8', function (err, data) {
    var re = /<p>[a-zA-Z1-9\s\r\n]*<\/p>/i;
    var myArray = data.match(re);
    console.log(myArray);
});

the result: '<p>Enter your phone number with area code and then click \\r\\n Check The expected format is like</p>'

But I want to use regular expresstion like below.

re = /<p>[.\r\n]*<\/p>/i;

But it print null. How to fix it? Why I can not use . to replace a-zA-Z1-9\\s thanks.

The reason is that a dot within a character class ( [...] ) looses its "superpowers" - meaning it is only a dot.
What you possibly want is re = /<p>[\\s\\S]+?<\\/p>/i; but please be warned that it is nod advisable to parse HTML structures with a regular expression:

 let html = ` <body> <p>Enter your phone number with area code and then click Check The expected format is like</p> <form action="#"> <input id="phone"><button onclick="testInfo(document.getElementById('phone'));">Check</button> </form> </body> </html>`; re = /<p>[\\S\\s]+?<\\/p>/i; var myArray = html.match(re); console.log(myArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM