Created
November 27, 2023 17:42
-
-
Save waptik/799dab0edf8fb7e8e11ff6eb52ba3f90 to your computer and use it in GitHub Desktop.
Ummmm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Certainly! Here's a TypeScript function that takes a text string as input and returns an array of code snippets found within code blocks wrapped in triple backticks(```) or `<code>`: | |
```typescript | |
function extractCodeSnippets(text: string): string[] { | |
const codeSnippets: string[] = []; | |
const regex = /```([\s\S]*?)```|<code>([\s\S]*?)<\/code>/g; | |
let match; | |
while ((match = regex.exec(text)) !== null) { | |
const codeSnippet = match[1] || match[2]; | |
codeSnippets.push(codeSnippet); | |
} | |
return codeSnippets; | |
} | |
``` | |
In this function, we use a regular expression (`/```([\s\S]*?)```|<code>([\s\S]*?)<\/code>/g`) to match code blocks wrapped in triple backticks or `<code>` tags. The `[\s\S]*?` pattern captures any characters (including newlines) within the code block. | |
We then use a `while` loop and the `exec()` method to iterate through all matches found in the input text. If a match is found, we check if `match[1]` or `match[2]` exists and assign the corresponding code snippet to the `codeSnippet` variable. Finally, we push the code snippet into the `codeSnippets` array. | |
You can use this function as follows: | |
```typescript | |
const text = ` | |
Here is some sample text. | |
\`\`\`javascript | |
function greet() { | |
console.log('Hello, world!'); | |
} | |
\`\`\` | |
Some more text. | |
<code> | |
const name = 'John Doe'; | |
console.log('Hello, ' + name); | |
</code> | |
Even more text. | |
`; | |
const snippets = extractCodeSnippets(text); | |
console.log(snippets); | |
``` | |
Running the above code will output: | |
``` | |
[ | |
"function greet() {\n console.log('Hello, world!');\n}", | |
"const name = 'John Doe';\nconsole.log('Hello, ' + name);" | |
] | |
``` | |
The `snippets` array contains the extracted code snippets from the input text. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment