gutenberg_ai_tools-1.0.x-dev/blocks/ai-block/parser.js

blocks/ai-block/parser.js
/* Utility class */

const checkForSampleCode = (text) => {
  let regex = /```[A-Za-z0-9]+/g;
  let found = text.match(regex);
  let finalCode = '';

  /* A Snippet of code was found, wrap it around <code> */
  if (found !== null && found.length > 0) {
    const beginCode = found[0];
    finalCode = text.replace(beginCode, '<code>');
    finalCode = finalCode.replace('```', '</code>');
  } else {
    return text;
  }

  // Check for more ``` elements inside the text
  regex = /```/g;
  found = finalCode.match(regex);

  if (found !== null && found.length > 0) {
    found.forEach((element, index) => {
      if (index % 2 === 0) {
        finalCode = finalCode.replace('```', '<code>');
      } else {
        finalCode = finalCode.replace('```', '</code>');
      }
    });
  }

  return finalCode;
};

const unicodeToChar = (text) => {
  return text.replace(/\\u[\dA-F]{4}/gi, (match) => {
    return String.fromCharCode(parseInt(match.replace(/\\u/g, ''), 16));
  });
};

const cleanUpSlashes = (text) => {
  let parsedData = '';
  parsedData = text.replace(/\\/g, '');

  return parsedData;
};

const parseAIResponse = (AIResponse) => {
  let parsedData = AIResponse.substring(1, AIResponse.length - 1);
  parsedData = unicodeToChar(parsedData.replace(/\\n/g, '<br />'));
  parsedData = checkForSampleCode(parsedData);
  parsedData = cleanUpSlashes(parsedData);

  /* eslint-disable-next-line prefer-template */
  return parsedData + '<br /><br />';
};

export default parseAIResponse;

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc