How to intercept multiple backticks notation in OpenAI response

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.

  • 1

    Does ChatGPT return your code in properly enclosed backticks? From the example, it looks like only the ending backticks are added and not the opening ones, but it could be a StackOverflow formatting issue.

    – 

  • Why do you use "```" instead of /```/ or /```/g? The first is not a regex!

    – 




Might be a bit overblown, but the function replaceAll below allows to pass in a mapping of characters and their replacement values and produces a new function that accepts an incoming string wherein characters are replaced.

const DATA = 'A string with ```backticks { some: foo; }\ntest::after { content: "bar"; }```';

const replaceAll = (replacementMapping) => {
  const replaceChars = Object.entries(replacementMapping);
  return (inputString) => {
    return replaceChars.reduce(
      (s, [oChar, nChar]) => s.replace(new RegExp(oChar, 'g'), nChar),
      inputString
    );
  };
};

const escaper = replaceAll({
  '`': '\\`',
  '"': '\\"'
});

console.log(escaper(DATA));

Plaats een reactie