快捷导航

JavaScript:实现JSON高亮代码块

xiarou 发表于 2023-1-18 05:30:18 | 显示全部楼层 |阅读模式
90 2
实现原理

使用正则表达式进行span标签的颜色替换

源代码
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSON高亮代码块</title>
    <style>
        #code {
            font-size: 32px;
            color: #e36209;
            font-family: 'Courier New', Courier, monospace;
            background: #f5f5f5;
        }

        .green {
            color: #22863a;
        }

        .blue {
            color: #005cc5;
        }

        .black {
            color: #032f62;
        }
    </style>
</head>
<body>
    <pre id="code"></pre>
    <script>
        // 核心算法
        function highlightJSON(json) {
            // 匹配key
            let keyReg = new RegExp("\"(.*)\"(?=", "g")
            // 匹配value
            let valueReg = new RegExp("(?<=: )(\"(.*)\"|\\d+)", "g")
            if (typeof json === "object" && json !== null) {
                json = JSON.stringify(json, this, 5)
            }
            // 颜色替换
            let res = json.replace(keyReg, (match) => {
                return `<span class="green">${match}</span>`
            }).replace(valueReg, (match) => {
                if (/\d/.test(match)) {
                    return `<span class="blue">${match}</span>`
                }
                return `<span class="black">${match}</span>`
            })
            return res
        }
        var json = {
            "name": "tailwindcss",
            "version": "1.0.0",
            "description": "",
            "main": "tailwind.config.js",
            "scripts": {
                "test": "echo \"Error: no test specified\" && exit 1"
            },
            "keywords": [],
            "author": "",
            "license": "ISC",
            "devDependencies": {
                "tailwindcss": "^3.1.3"
            }
        }
        document.getElementById("code").innerHTML = highlightJSON(json)
    </script>
</body>
</html>

回复

使用道具 举报

全部回复(3)
大佬有什么好项目合作吗?
  • 海!外直播 v.ht/99994 禁闻视频 v.ht/35555 阿伦特说:“权威的最大敌人是轻蔑,而破坏它的最有效的方法是嘲笑。”看看网络,这已经是一个全民对“伟大光荣正确”群嘲时代...
    2023-2-17 04:55
2023-1-18 05:30:18
看不懂
2023-1-18 05:41:02
您需要登录后才可以回帖 登录 | 立即注册

Archiver|小黑屋|关于我们

Copyright © 2001-2021, Tencent Cloud.    Powered by Discuz! X3.5

违法和不良信息举报电话:010-00000000 举报邮箱:adminx@adminx.com 未成年人不良信息举报电话:010-00000000

GMT+8, 2023-3-23 04:10 , Processed in 0.028682 second(s), 38 queries .