2

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]
3
  • You can try split()ing on "```". Commented May 30, 2018 at 4:34
  • 1
    the easiset is to render to a fragment, then use the dom/css selectors to hit it. Commented May 30, 2018 at 4:38
  • @dandavis Would you like to explain more about this? Commented May 31, 2018 at 2:04

2 Answers 2

2

You can try doing it with regular expression

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

var code = s.match(/```(.*)```/)[1]
Sign up to request clarification or add additional context in comments.

4 Comments

Remember to .trim() the result :)
preferrably use ([^`]*) or you will get unwanted results if the string includes several code blocks.
@ASDFGerte You mean that the regex is like this, /```([^`]*)```/?
Yes. Try both with "```console.log()```Hello```console.log()```Hello".match( and you will see the difference.
1

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

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.