我正在尝试匹配代码块以检查是 html 还是 javascript 代码,我尝试这样做但是当有这个 html 元素时遇到问题 "<div></div>"
或 php <? echo '';>
在 javascript 代码中,它将匹配它作为 html 元素。
有人可以帮我提供最好的归档方法吗?
<script>
$(document).ready(function(){
function AssignLang(theLanguage){
var regex = /(<([^>]+)>|<([^>]+)>)/ig;
//var regex = "<(\"[^\"]*\"|'[^']*'|[^'\">])*>";
if(theLanguage.match(regex)){
var lang = 'markup';
}else{
var lang = 'javascript';
}
return lang;
}
$('pre code').each(function () {
var the = $(this).html();
/*I tried here to match from 0 to 50 but is not going to help because if the javascript tag begin with <script> still show as html
var theLanguage = the.replace(/\s/g, '').substring(0,50);
*/
var theLanguage = the.replace(/\s/g, '');
var langType = AssignLang(theLanguage);
$(this).addClass("fullcoded language-"+langType);
alert(theLanguage+"-"+langType);
});
});
</script>
这里是 pre 和 code 元素中的匹配代码
<pre><code>
function check() {
var delvar = "<? $_POST["del"]; ?>";
var answer = confirm("Are you sure you want to delete the article?")
if (answer) {
window.location = "adm-site.php?del=" + delvar + "&delete=true";
}
}
</code></pre>
<pre><code>
<select name="del">
<option value="none" SELECTED></option>all articles echo'ed here by php
</select>
</code></pre>
这里是 https://jsfiddle.net/ppu9qw3n/ 的链接
最佳答案
这是我正在使用的正则表达式 /\w+\s\w+\(\)/i
\w+ 匹配 1 个或多个 a-z、A-Z、0-9 和 _
\s 匹配 1 个空格
\( 和\) 匹配 ()
基本上,我在代码标签之间的代码中搜索由 function functionName()
组成的模式。如果找到匹配项,则它是 JavasScript 代码,否则就是 HTML 代码。
这是实现 JavaScript 的方式:
$(document).ready(function(){
var regex = /\w+\s\w+\(\)/i;
$('pre code').each(function () {
var v = $(this).html();
if(regex.test(v)){
alert(v+'-'+'THIS IS JAVASCRIPT CODE')
}
else{
alert(v+'-'+'THIS IS HTML CODE')
}
});
});
在 jsfiddle 上查看。它的工作。 https://jsfiddle.net/swzaf5r1/
关于javascript - 识别代码标签之间的代码是 JavaScript 还是 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40809621/