<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box{
width: 600px;
height: 600px;
}
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; } /*字符串的样式*/
.number { color: darkorange; } /*数字的样式*/
.boolean { color: blue; } /*布尔型数据的样式*/
.null { color: magenta; } /*null值的样式*/
.key { color: red; } /*key值的样式*/
</style>
</head>
<body>
<div class="box">
<pre id="result"></pre>
</div>
<script>
function syntaxHighlight(json) {
if (typeof json != 'string') {
json = JSON.stringify(json, undefined, 2);
}
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?)/g,
function(match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
}
);
}
var dom = document.querySelector("#result")
dom.innerHTML = syntaxHighlight('{\n "a": 1,\n "b": 2,\n "c": {\n "d": "asdfsdf",\n "aaa": true\n },\n "aa": [\n {\n "id": null\n }\n ]\n}')
</script>
</body>
</html>
HTML中代码高亮显示
于 2023-11-08 14:25:26 首次发布
本文展示了一个JavaScript函数,用于在HTML中高亮显示JSON字符串,包括不同类型的值(如数字、字符串、布尔和null)。通过`syntaxHighlight`函数,代码被格式化以提高可读性。
摘要由CSDN通过智能技术生成