-1

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.

MrCoder74
  • 40
  • 4
  • 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. – 5px Aug 21 '23 at 08:42
  • Why do you use `"```"` instead of `/```/` or `/```/g`? The first is not a regex! – Bergi Aug 21 '23 at 09:53
  • shame on me, it was so obvious :( thank you i guess my mind was so dizzy after 3 hours spent arranging the functions, and i got lost in a glass of water :-\ – MrCoder74 Aug 21 '23 at 11:48

2 Answers2

0

Thanks to Bergi's comment i found out i had used the wrong approach for the second replace. Thank you all for your time.

MrCoder74
  • 40
  • 4
-1

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));
David
  • 3,552
  • 1
  • 13
  • 24