Forum Moderators: open
// comment here
I'm having problems with the regular expression needed to do this. Here's what I'm using:
/^[\/]{2}.*[\n]$/g
According to my notes and Javascript manuals, this should search for any string that begins with two forward slashes, followed by any number of other characters and then terminates with a line break.
The results I'm getting are:
// test [no line break] = // test (GOOD)
// test [line break] = [nothing] (GOOD)
// test [line break] keep me = // test [line break] keep me (NO GOOD)
What's wrong with my regular expression? I don't get it. I'm climbing the walls here.
Just for posterity, here's the test case scenario-
<html>
<head>
<script type="text/javascript">
function stripComments () {
var inputCode = document.getElementById("inputCode").value;
var regex_sc1 = /^[\/]{2}.*[\n]$/g;
var noComments = inputCode.replace(regex_sc1,"");
document.getElementById("outputCode").value = noComments;
}
</script>
</head>
<body>
<form action="">
INPUT CODE:<br>
<textarea id="inputCode" rows="10" cols="50"></textarea><br>
<button type="button" onclick="stripComments();">Strip Comments</button><br>
<br>
OUTPUT CODE:<br>
<textarea id="outputCode" rows="10" cols="50"></textarea><br>
<input type="reset">
</form>
</body>
</html>
If I've understood you correctly, you only want to remove comments in the beginning of a line.
This works fine for me:
var regex_sc1 = /(^[\/]{2}[^\n]*)¦([\n]{1,}[\/]{2}[^\n]*)/g;
The second alternative matches // preceded by a newline. The first alternative takes care of the case when the first line is a comment. In this (and only this) latter case a newline will remain though.
J
/(^[\/]{2}[^\n]*)¦([\n]{1,}[\/]{2}[^\n]*)/g;
..as I understand it means, search for a double forward slash at the beginning and then any number of new line characters also at the beginning (of what?) which is evaluated before the former OR search for a new line character 1 or more times followed by a double forward slash followed by any number of new line characters at the beginning of something again (huh?)... (*chuckle*)... Sheesh... works fine but what a mind boggler!
The ^[\/]{2}[^\n]*) matches a double forward slash in the beginning of the string, followed by any characters except new line (placed inside a character set ^ negates the subsequent characters, ie [^\n] means ANY character BUT new line.
The [\n]{1,}[\/]{2}[^\n]* part matches one or more new line followed by a double forward slash, followed by any characters except new line.