<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta charset="utf-8" /> <title>提取代码注释</title> <script src="https://ss.netnr.com/@highlightjs/cdn-assets@11.9.0/highlight.min.js"></script> </head> <body> <pre> // a. 定义一个变量 let name = "bill"; // b. 再来一个 let url = "wss://www.v2ex.com"; // c. 注意:url 需要添加 "wss://" 协议 // d. 多行文本 let content = `Javascript 支持多种注释, 其中,双斜杠 // 表示单行注释, /* ... */ 表示多行注释`;</pre> </body> </html>
* { color: deeppink; }
function getComment(code, lang) { var pout = hljs.getLanguage(lang) ? hljs.highlight(code, { language: lang }).value : hljs.highlightAuto(code).value; var cnode = document.createElement("div"); cnode.innerHTML = pout; var comments = []; cnode.querySelectorAll('.hljs-comment').forEach(item => { comments.push(item.innerHTML); }); return comments; } var cmts = getComment(document.querySelector('pre').innerHTML, 'js'); cmts.forEach(c => console.log(c))