skip to Main Content

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.

2

Answers


  1. Chosen as BEST ANSWER

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


  2. 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));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search