简体   繁体   中英

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]

You can try doing it with regular expression

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

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

Look at follow regex, it's match all your strings:

/```[^`]*```/gmi

Working example can be found here https://regex101.com/r/hcRumt/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM