View Full Version : Resolved Javascript: make regular expression ignore new lines

Running Bear
Nov 7th, 2009, 10:27 AM

Does anyone know how to make a javascript regex ignore new lines?

I have this

html = html.replace(/<!--(.*?)-->/gi, ''); // HTML comments
which matches single line comments like -

<!-- this is a comment -->

but not this -

This is a comment
on multiple lines

I think the answer lies with [\s\S] but I can't get it to work

e.g. -

html = html.replace(/<!--(.*[\s\S]?)-->/gi, ''); // HTML comments

Any help will be greatly appreciated

Cheers Al

Philip M
Nov 7th, 2009, 12:13 PM
These examples should help you:-

<textarea id = "html" rows = 5" cols = 40" onblur = "removeHTMLComments(this.value)">Hello
This is a comment
on multiple lines

<script type = "text/javascript">

function removeHTMLComments(html) {
alert (html.replace(/<!(?:--[\s\S]*?--\s*)?>\s*/g,'')); // for testing
return html.replace(/<!(?:--[\s\S]*?--\s*)?>\s*/g,'');


<div id="test">
<!-- Hello Philip -->Real Text Here
<!-- Here is a comment
on multiple
lines -->
<span>Something within in a nested tag<!-- There another comment
on multiple lines --></span>
<input type="button" onclick="alert(document.getElementById('test').innerHTML.replace(/<!--[^(-->)]+-->/g, ''));" value="Go!">

He thought he saw a Garden-Door
That opened with a key:
He looked again, and found it was
A Double Rule of Three:
"And all its mystery," he said,
"Is clear as day to me!"
- Lewis Carroll

Running Bear
Nov 7th, 2009, 12:26 PM

Thanks a whole bunch. Much appreciated

Cheers Al