Code:
/*!
* html-css-js discrimination by zzbaivong (devs.forumvi.com)
* @param source {String} Source code
*/
function hcjDiscrimination(source) {
// detect HTML/template
if (/^[\s\n]*({[a-zA-Z_\.]+})*[\s\n]*<[\s\S]+>[\s\n]*({[a-zA-Z_\.]+})*[\s\n]*$/.test(source)) {
return "html";
} else { // not HTML/template
// Remove block comment
source = source.replace(/\/\*.*\*\//gm, "");
// symbol comment // only use by javascript
if (/^\s*\/\/.*$/m.test(source)) {
return "js";
}
// The methods used in javascript can insert internal style sheet
if (/(document|window)(\.|,|\))|\.createElement|\.getElementsByTagName|\.insertBefore|\.parentNode|\.getElementBy|\.innerHTML|\.innerText|\.textContent/m.test(source)) {
return "js";
}
// The signs easily seen javascript
if (/(\$|jQuery)(\(|\.)|var\s*[\w\-]+\s*=|function\s*[\w\-]*\s*\(|[\w\-\.]\s*=\s*{|^return(\s|"|'|{)|}\s?else(\sif)?\s?{/m.test(source)) {
return "js";
}
// CSS at-rule
if (/^@charset\s[\w\-'"]+;/m.test(source)) {
return "css";
}
if (/^@import[\w\-,\(\):\s\.\/'"]+;/m.test(source)) {
return "css";
}
if (/^@media[\w\-,\(\):\s]+[\s\n]*{/m.test(source)) {
return "css";
}
if (/^@(font\-face|viewport)[\s\n]*{/m.test(source)) {
return "css";
}
if (/^@namespace(\s[\w\-]+)?\surl\(https?:\/\/[\w\.\-\/]+\);/m.test(source)) {
return "css";
}
if (/^@supports[^\n,;_{}\<\>][\s\n]*{|@page\s:{1,2}[a-z\-\(\)\d]+[\s\n]*{/m.test(source)) {
return "css";
}
if (/^@(\-(ms|moz|webkit)\-)?keyframes\s[\w\-]+[\s\n]*{/m.test(source)) {
return "css";
}
// Css property
if (/^[a-z\-]+\s*:[^\n'";]+;$/m.test(source)) {
return "css";
}
if (source.search(/{[^}]+}/) > 0) {
if (/((\*|([a-z]+[1-6]?)?((\#|\.)[\w\-]+)*(\[[a-z\-]+((\*|\||\>|\+|~|\^|\$)?=('|")?[^\n\]\>"']*('|")?)?\])*(:{1,2}[a-z\-\(\)\d]+)*)\s?(\+|\>|~|,)?\s?)+[\s\n]*{([\s\n]*[a-z\-]+\s*:\s*[^;\n}]+\s*;?[\s\n]*)+}/m.test(source)) {
return "css";
}
}
// Not css or html
return "js";
}
}
// Show result
$("button").click(function () {
alert(hcjDiscrimination($("textarea").val()));
});