Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regular expression string-replacement of multi-line strings

With JavaScript regular expression replace, trying to replace anything between <head> and </head> tags so that:

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

gets replaced into:

<body>
  Multi line bar
</body>

and trying with the very basic: <head(.*)\/head>/m which doesn't work. It works fine when line breaks are removed from string. No matter what type of line breaks, what's the magic?

like image 664
Rushen Bilgin Avatar asked Dec 17 '22 18:12

Rushen Bilgin


1 Answers

The problem is that the dot metacharacter doesn't match newlines. In most regex flavors you can force it to match everything by setting "DOTALL" or "single-line" mode, but JavaScript doesn't support that. Instead, you have to replace the dot with something that does match everything. The most common idiom is [\s\S] ("any whitespace character or any character that's not whitespace").

like image 110
Alan Moore Avatar answered Dec 19 '22 06:12

Alan Moore