I am learning java script and am currently learning regex. I study on my own and practice. I have some random code from the C program in which there is a for loop, I want to use java script and regex to replace the for loop in the while loop. If I change the code in the while loop when I click the button, how do I do that?
ps. I know the questions are weird and beginner but I’m just just learning and want to learn
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="content">
<code>
#include
int main() {
int i,x;
scanf("%d", &x);
for (i=1; i<=10; i++) {
printf("%d %d\n", i, pow(x,i));
}
return 0;
}
</code>
</div>
<div class="container">
<div>
<button id="btnText">Klikni</button>
</div>
</div>
<script src="java.js"></script>
</body>
</html>
The regex works only for simple cases. If you have braces inside of the loop, will not work. The logic:
<SPACE_>for<SPACE_OPTIONAL>( (the first space is group 1, and is to prevent catching false positives, like function with name myFuncWithSufix_for(params));; (group 2, containing the assign variable);; (group 3, containing the condition);) (group 4, containing the increment);{ and } (group 5, containing the loop body);The flag g, means global, and will apply this regex multiple times if you have multiple for loops;
After this, the replace is trivial :)
function replaceForLoopIntoWhileLoop(){
var code = document.getElementById('content').children[0].innerText;
var newCode= code.replace(/(\s)for\s*\(([^;]+);([^;]+);([^)]+)\)\s*\{([^}]*)\}/g, '$1$2;\nwhile($3) {\n$5\n$4;\n}');
document.getElementById('content').children[0].innerText = newCode;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div id="content">
<code>
#include
int main() {
int i,x;
scanf("%d", &x);
for (i=1; i<=10; i++) {
printf("%d %d\n", i, pow(x,i));
}
return 0;
}
</code>
</div>
<div class="container">
<div>
<button id="btnText" onclick="replaceForLoopIntoWhileLoop()">Klikni</button>
</div>
</div>
<script src="java.js"></script>
</body>
</html>