Issue
I am trying to integrate dynamic response as event/stream (coming from a gpt api). Event source is printing properly but all as text. out of them have code snippet with triple backticks as
```javascript
var s = "JavaScript syntax highlighting";
window.alert(s);
var num = 42;
```
but it is not highlighting , I have used highlight.js lib but only syntax inside pre code is highlighted which I added manually. But I need dynamic highlighting. here is what I did.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Example</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css">
</head>
<body>
<p style="white-space: pre-wrap">
```javascript
var s = "JavaScript syntax highlighting"; //not highlighiting
window.alert(s);
var num = 42;
```
<pre><code class="language-javascript">
var s = "JavaScript syntax highlighting"; //highlighiting
window.alert(s);
var num = 42;
</code></pre>
</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
</body>
</html>
where am I going wrong...any way or alternative. Please suggest.
Solution
You can use a RegEx to find and replace those.
const regexCode = /```(?<lang>\w*)\n+(?<code>.*?)```/gs
let rawText = document.querySelector("p").innerHTML
document.querySelector("p").innerHTML = rawText.replaceAll(regexCode, '<pre><code class="language-$1">$2</code></pre>')
<p style="white-space: pre-wrap">
```javascript
var s = "JavaScript syntax highlighting"; //not highlighiting
window.alert(s);
var num = 42;
```
</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script>hljs.highlightAll();</script>
Answered By - ChalanaN
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.