Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a regular expression that replaces strings in quotes with empty strings

How can I create a regular expression that finds the text wrapped in """ or ''' for example:

hello """
long text here,
e.g. a private SSH key
"""
this is a name for testing

'''
this is another multi-line 
stuff.
'''

I want to get the output like:

hello
this is a name for testing

With all the text that are in """ or ''' replaced with an empty string.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use """|''' as delimiters (with a \1 back-reference for the closing one), a non-greedy match-all (.*?) and the s (dot-all) and g (global) flags.

Remove leading and trailing white-space with trim().

const str = `hello """
long text here,
e.g. a private SSH key
"""
this is a name for testing

'''
this is another multi-line 
stuff.
'''`

console.log(str.replace(/("""|''').*?\1/gs, "").trim());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading