我要做的是选择除了注释之外的每一行javascript代码(只是注释/ **到* /在beginnig中有或没有空格)并替换为单词(代码)。我需要使用RegEx并替换javascript函数。
例如
/**
* Source Code
*/
/**
* Places given shatter objects images into the specified dom element
*
* @param {object} shatter - Shatter object
* @param {object} domElement - The dom element to append images to
*/
function placeShatter (shatter, domElement) {
// adjustment to center image on screen
var adjustment = (window.innerWidth / 2) * image.width / 2;
for (var i = 0; i < shatter.images.length; i++) {
placeImageAbsolute(shatter.images[i].image,
domElement,
shatter.images[i].x,
shatter.images[i].y,
adjustment,
YLOC);
}
}
/**
* Source Code
*/
/**
* Places given shatter objects images into the specified dom element
*
* @param {object} shatter - Shatter object
* @param {object} domElement - The dom element to append images to
*/
(code)
(code)
(code)
(code)
(code)
(code)
(code)
(code)
(code)
(code)
(code)
(code)
(code)
RegEx必须使用此代码:
<!DOCTYPE html>
<html>
<body>
<p>Source Code</p>
<textarea rows="50" cols="150" id="input"></textarea>
<p>Click the button to perfom a global replacement and display the matches.</p><button onclick="myFunction()">Try it</button>
</br>
<textarea rows="50" cols="150" id="output"></textarea>
<script>
function myFunction() {
var not_comments = document.getElementById("input").value.replace(RegEX,'(code)');
document.getElementById("output").value = not_comments;
}
</script>
</body>
</html>
答案 0 :(得分:0)
如果您想要消除它,您可以捕获它并进行替换。
例如:
var text = "/** TEST */ stuff";
text.replace(/(\/\*\*[\s\S]*\*\/)/g, '');
要打破它:
(\/\*\* //This Matches /** with the start of a capture group
[\s\S]* //This Matches ANY character (including line endings) zero or more times.
\*\/) //This matches */ and closes the group
将采用该文本并将/ ** TEST * /替换为空格。
以下是一个示例:https://regex101.com/r/xA1yY5/1
但是,如果你正在处理大文件,你最好用文件阅读器读取文件并写入新文件而不包括注释。这可以通过创建一个标志来完成,当你按下/ **并且不允许写入时它会打开然后如果它击中* /并且允许再次写入则关闭。
答案 1 :(得分:0)
答案 2 :(得分:0)
这是我最后的方法:
<!DOCTYPE html>
<html>
<body>
<p>Source Code</p>
<textarea rows="50" cols="150" id="input"></textarea>
<p>Click the button to perfom a global replacement and display the matches.
</p><button onclick="myFunction()">Try it</button>
</br>
<p>Output</p>
<textarea rows="50" cols="150" id="output"></textarea>
<p>Output without blank lines</p>
<textarea rows="50" cols="150" id="output_without_blank_lines"></textarea>
<script>
function myFunction() {
var code = "(code)"
var withoutspaces = document.getElementById("input").value.replace(/^ +/gm, '');
var regex = /\/\*[\s\S]*?\*\/|(^[\s\S]*?$)/gm;
var replaced = withoutspaces.replace(regex, function(m, group1) {
if (group1) return code;
else return m;
});
document.getElementById("output").value = replaced;
document.getElementById("output_without_blank_lines").value = replaced.replace(/^[ \t]*$\r?\n/gm,code+'\n');
}
</script>
</body>
</html>
&#13;