[英]Remove comments with replace in JavaScript
I am hoping to remove all comments from a DNS zone file with JavaScript.我希望使用 JavaScript 从 DNS 区域文件中删除所有评论。 The comments start with a semicolon (
;
) in a DNS zone files.在 DNS 区域文件中,注释以分号 (
;
) 开头。 However, I also don't want the semicolons being replaced if they are preceded by a back slash.但是,如果分号前面有反斜杠,我也不希望分号被替换。 I have some test code which looks like this:
我有一些测试代码如下所示:
var record = 'example.com IN TXT "v=DKIM1\\; k=rsa\\; p=MIGf..."';
var recordWithCommentRemoved = record.replace(/[^\\];[\s\S]*?$/gm, '');
console.log(recordWithCommentRemoved); // example.com IN TXT "v=DKIM1\; k=rsa\; p=MIGf..."
The code above works as expected.上面的代码按预期工作。 However, the following code replaces one more character than expected:
但是,以下代码比预期多替换了一个字符:
var record = 'test 300 IN A 100.100.100.100;this is a comment';
var recordWithCommentRemoved = record.replace(/[^\\];[\s\S]*?$/gm, '');
console.log(recordWithCommentRemoved); // test 300 IN A 100.100.100.10
In the second example, what I expected is test 300 IN A 100.100.100.100
.在第二个示例中,我期望的是
test 300 IN A 100.100.100.100
。 However, it returns test 300 IN A 100.100.100.10
.但是,它返回
test 300 IN A 100.100.100.10
。 So what's wrong with my regular expression?那么我的正则表达式有什么问题呢?
You need to make sure the ;
你需要确保
;
is not preceded with a \
, thus, use a (^|[^\\])
group before ;
前面没有
\
,因此,在 之前使用(^|[^\\])
组;
and replace using a callback:并使用回调替换:
var re = /(^|[^\\]);.*/g; var str = 'example.com IN TXT "v=DKIM1\\; k=rsa\\; p=MIGf..."\ntest 300 IN A 100.100.100.100;this is a comment'; var result = str.replace(re, function(m, g1){ return g1? g1: ""; // if g1 is set/matched, re-insert it, else remove }); document.body.innerHTML = result.replace(/\n/g, "<br/>"); // just for display
The regex matches:正则表达式匹配:
(^|[^\\])
- (capture group #1) start of string ( ^
) or ( |
) any character but a \
( [^\\]
) (^|[^\\])
-(捕获组 #1)字符串开头 ( ^
) 或 ( |
) 除\
( [^\\]
) 之外的任何字符;
- a literal ;
;
.*
- zero or more characters other than a newline .*
- 除换行符外的零个或多个字符This too removes all comments using replace.这也删除了所有使用替换的评论。
$("#doc").keyup(function(evt) { var doc = $("#doc").val(); var documentNew = String(doc).replace(/(\r\n|\n|\r)/gm, "\n"); var str = documentNew; var lines = str.split('\n'); var filterred = lines.filter(function(line) { return line.indexOf('//');= 0; }). filterred = String(filterred);replace(/,/g; "; \n"). $("#answerDocument2");html(filterred); });
textarea { width: 200px; height: 200px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h3>Paste Code</h3> <textarea id="doc"></textarea> <h3>Copy Formatted Code</h3> <textarea id="answerDocument2" readonly style="resize: none;"></textarea>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.