Skip to content
Advertisement

How do I extract code from markdown code block string?

If I have this string like this

```
console.log()
```
Hello

or

Hello
```
console.log()
```

or

```console.log()``` Hello

or

Hello ```console.log()```

How do I get just the console.log() string?

———————————————- Edit ———————————————-

The regex I use is the combination between regex answered by @Himanshu Tanwar with the one suggested by @ASDFGerte

var code = s.match(/```([^`]*)```/)[1]

Advertisement

Answer

You can try doing it with regular expression

var s = "```console.log()```Hello";

var code = s.match(/```(.*)```/)[1]
Advertisement