js 玩转正则表达式之语法高亮(4)

function prettify(node) {
        var code = node.innerHTML.replace(/\r\n|[\r\n]/g, "\n").replace(/^\s+|\s+$/g, "");
        code = code.replace(_re_js, function() {
            var s, a = arguments;
            for (var i = 1; i <= 7; i++) {
                if (s = a[i]) {
                    s = htmlEncode(s);
                    switch (i) {
                        case 1: //注释 com
                            return '<span>' + s + '</span>';
                        case 2: //字符串 str
                            return '<span>' + s + '</span>';
                        case 3: //true|false|null|undefined|NaN val
                            return '<span>' + s + '</span>';
                        case 4: //关键词 kwd
                            return '<span>' + s + '</span>';
                        case 5: //内置对象 obj
                            return '<span>' + s + '</span>';
                        case 6: //数字 num
                            return '<span>' + s + '</span>';
                        case 7: //正则 reg
                            return htmlEncode(a[0]).replace(s, '<span>' + s + '</span>');
                    }
                }
            }
            return htmlEncode(a[0]);
        });
        code = code.replace(/(?:\s*\*\s*|(?:&nbsp;)*\*(?:&nbsp;)*)(@\w+)\b/g, '&nbsp;*&nbsp;<span>$1</span>') // 匹配注释中的标记
                   .replace(/(\w+)(\s*\(|(?:&nbsp;)*\()|(\w+)(\s*=\s*function|(?:&nbsp;)*=(?:&nbsp;)*function)/g, '<span>$1</span>$2') // 匹配函数
        return code;
    }


    function htmlEncode(str) {
        var i, s = {
                //"&amp;": /&/g,
                "&quot;": /"/g,
                "&#039;": /'/g,
                "&lt;": /</g,
                "&gt;": />/g,
                "<br>": /\n/g,
                "&nbsp;": / /g,
                "&nbsp;&nbsp;": /\t/g
            };
        for (i in s) {
            str = str.replace(s[i], i);
        }
        return str;
    }

window.prettify = prettify;
})(window);
</code>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wfywws.html