PDA

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



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

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
-->
</textarea>

<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,'');
}

</script>


<html>
<head>
</head>
<body>
<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>
</div>
<input type="button" onclick="alert(document.getElementById('test').innerHTML.replace(/<!--[^(-->)]+-->/g, ''));" value="Go!">
</body>
</html>


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
Philip,

Thanks a whole bunch. Much appreciated

Cheers Al