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

<script>
(function(window, undefined) {
    var _re_js = new RegExp('(\\/\\/.*|\\/\\*[\\s\\S]*?\\*\\/)|("(?:[^"\\\\]|\\\\[\\s\\S])*"|\'(?:[^\'\\\\]|\\\\[\\s\\S])*\')|\\b(true|false|null|undefined|NaN)\\b|\\b(var|for|if|else|return|this|while|new|function|switch|case|typeof|do|in|throw|try|catch|finally|with|instance|delete|void|break|continue)\\b|\\b(document|Date|Math|window|Object|location|navigator|Array|String|Number|Boolean|Function|RegExp)\\b|(?:[^\\W\\d]|\\$)[\\$\\w]*|(0[xX][0-9a-fA-F]+|\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?|\\.\\d+(?:[eE][+-]?\\d+)?)|(?:^|[^\\)\\]\\}])(\\/(?!\\*)(?:\\\\.|[^\\\\\\/\\n])+?\\/[gim]*)|[\\s\\S]', 'g');

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;
    }

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

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