<code><pre id='output'></pre></code>
@import url('https://fonts.googleapis.com/css2?family=Fira+Code:[email protected];400&family=Poppins:[email protected];300;400;500&display=swap');
/* Box sizing rules */
*,
*::before,
*::after {
box-sizing: border-box;
}
body {
background-color: hsl(0 0% 15%);
display: flex;
color: hsl(0 0% 80%);
justify-content: center;
}
code {
max-width: 800px;
width: 100%;
background-color: hsl(0 0% 10%);
border-radius: 10px;
padding: 1rem 2rem;
}
pre {
width: 100%;
font-family: 'Fira Code', monospace;
font-weight: 400;
color: hsl(0 0% 85%);
white-space: pre-wrap;
.strings {
color: hsl(100 20% 60%);
}
.regex {
color: hsl(100 20% 60%);
}
.comments {
color: hsl(230 20% 60%);
}
.spread {
color: hsl(308 15% 60%);
}
.props {
color: hsl(308 15% 60%);
}
.keywords {
color: hsl(59 60% 70%);
}
.brackets {
color: hsl(310 60% 50%);
}
}
View Compiled
const tokens = [
'(?<strings>([\\u0027"`])[\\s|\\S]*?(?<!\\u005C)\\2)',
'(?<comments>(?<!:)\\u002F{2}.*|\\u002F\\u002A[\\s\\S]*?\\u002A\\u002F)',
'(?<regex>(?<!\\/)\\/[^\\/]+\\/[a-zA-Z]{0,3})',
'(?<spread>(\\.{3}))',
'(?<props>(?<=\\w\\.)\\w+)',
'(?<numbers>\\b\\d+(?:\\.\\d+)?\\b)',
'\\b(?<keywords>abstract|arguments|await|boolean|break|byte|case|catch|char|class(?!=\s*?=)|const|continue|debugger|default|delete|do|double|else|enum|eval|export|extends|false|final|finally|float|for|function|goto|if|implements|import|in|instanceof|int|interface|isNaN|let|long|native|new|null|package|private|protected|public|return|short|static|super|switch|synchronized|this|throw|throws|transient|true|try|typeof|undefined|var|void|volatile|while|with|yield)\\b',
'\\b(?<builtIn>Object|Array|Function|String|Number|null|undefined|Symbol|BigInt)\\b',
'(?<brackets>[\\{\\(\\[\\]\\)\\}])'
]
// join all regexes
const tokensRx = new RegExp(tokens.join('|'), 'gm')
const highlightJS = (markup) => {
return markup.replaceAll(tokensRx, (...args) => {
// last index contains named matches e.g.
// { string: undefined, comment: '// comment here', regex: undefined ...}
const [matches] = args.slice(-1)
for (const tokenType in matches) {
if (matches[tokenType] !== undefined) {
const span = document.createElement('span')
span.className = tokenType
span.textContent = matches[tokenType]
return span.outerHTML
}
}
})
}
(async() => {
// import a text file containing the raw code
const response = await fetch('https://assets.codepen.io/3351103/sample-code.txt')
const code = await response.text()
document
.querySelector('#output')
.insertAdjacentHTML('afterbegin', highlightJS(code.trim()))
})()
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.