I have written a simple OpenAI based chatbot in JS, but i want to intercept the backticks indicating the language in the chatbot response... in both opening and close I have tried multiple regexes, i came out with the following:
fetch(API_URL, requestOptions)
.then(res => res.json())
.then(data => {
messageElement.textContent = data.choices[0].message.content.trim();
// Find and replace tml, ss, and avascript
messageElement.textContent = messageElement.textContent.replace(/```(html|css|javascript)(.*?)/gs, '$2');
messageElement.textContent = messageElement.textContent.replace("```", "");
})
.catch(() => {
messageElement.classList.add("error");
messageElement.textContent = "Oops! Something went wrong. Please try again.";
})
.finally(() => chatbox.scrollTo(0, chatbox.scrollHeight));
The problem is it works well but at the end of the code the last backticks closing line is not replaced. I.E. if i ask for a css navbar code, i get:
CSS (salvato in un file chiamato "style.css"):
nav { background-color: #333; }
nav ul { list-style-type: none; margin: 0; padding: 0;
overflow: hidden; }nav li { float: left; }
nav li a { display: block; color: white; text-align: center;
padding: 14px 16px; text-decoration: none; }nav li a:hover { background-color: #111; } ```
Anybody has an idea on how to solve this? Thanks in advance. Alex.