Javascript regex string - multiline string replacement

With a JavaScript regular expression replacement trying to replace something between the <head> and </head> tags so that:

 <head> Multiline foo </head> <body> Multi line bar </body> 

replaced by:

 <body> Multi line bar </body> 

and tries with the simplest: <head(.*)\/head>/m , which does not work. It works great when line breaks are removed from a line. No matter what type of line breaks that magic?

+4
source share
2 answers

The problem is that the dot metacharacter does not match newlines. In most varieties of regular expressions, you can make it match everyone by setting it to "DOTALL" or "single-line", but JavaScript does not support this. Instead, you need to replace the dot with what matches . The most common idiom is [\s\S] ("any space character or any character, not a space").

+8
source

Alan is right to take stock, use /<head([\s\S]*)\/head>/ , and he should do what you want.

The actual regex that I would use for the job is /<head>([\s\S]*?)<\/head>/ , but the difference will probably not matter, as it just ensures that there is no greedy matching with the 2nd heading, which should never be :)

+4
source

Source: https://habr.com/ru/post/1336124/


All Articles