Skip to content

Instantly share code, notes, and snippets.

@waptik
Created November 26, 2023 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waptik/33225be1dee8fe462b7d61897336db51 to your computer and use it in GitHub Desktop.
Save waptik/33225be1dee8fe462b7d61897336db51 to your computer and use it in GitHub Desktop.
chatgpt response from api
Certainly! Here's a TypeScript function that takes a text as input and returns an array of code snippets found within multiple lines code blocks wrapped in triple backticks (```) or `<code>` tags with language tags:
```typescript
function extractCodeSnippets(text: string): { language: string, code: string }[] {
const codeBlockRegex = /```(\w+)\n([\s\S]*?)```|<code(?:\s+class="language-(\w+)")?>([\s\S]*?)<\/code>/g;
const codeSnippets: { language: string, code: string }[] = [];
let match;
while ((match = codeBlockRegex.exec(text)) !== null) {
const [, language1, code1, language2, code2] = match;
const language = language1 || language2 || '';
const code = code1 || code2 || '';
codeSnippets.push({ language, code });
}
return codeSnippets;
}
```
This function uses a regular expression (`/```(\w+)\n([\s\S]*?)```|<code(?:\s+class="language-(\w+)")?>([\s\S]*?)<\/code>/g`) to match multiple lines code blocks wrapped in triple backticks or `<code>` tags with optional language tags within the given text. It captures the language tag (if present) and the code snippet within the code block or `<code>` tag. It then iterates over all matches and extracts the language and code, storing them as objects in an array. The function returns the array of code snippets with their corresponding language tags.
Here's an example usage of the function:
```typescript
const text = `
This is a text with code blocks:
\`\`\`html
<h1>Hello, world!</h1>
\`\`\`
Some other text...
<code class="language-js">
const message = 'This is a code block in JavaScript';
console.log(message);
</code>
More text...
`;
const snippets = extractCodeSnippets(text);
snippets.forEach(snippet => {
console.log(`Language: ${snippet.language}`);
console.log(`Code: ${snippet.code}`);
console.log('---');
});
```
In this example, the `extractCodeSnippets` function is used to extract code snippets with language tags from the given `text`. It then logs the language and code of each snippet to the console.
Feel free to modify this function to fit your specific needs or enhance it further as required.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment