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

How to extract a specific substring (based on regex) from an array of strings

I have a big array of strings:

['{{Wanted Value}}', 'true', '{{Wanted Value}}', '{{Wanted Value}} unwanted {{Wanted Value}}', 'false'...]

I want to filter the array and extract every {{Wanted Value}} substring to a new array. If the item in the array contains 2 or more of these substrings, I want to have each of them as a separate item. So the result of the above array would be:

['{{Wanted Value}}', {{Wanted Value}}', {{Wanted Value}}', {{Wanted Value}}']

I wrote the regex I want to use but not sure how to write the filter function correctly:

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

match(/\{\{(.+?)\}\}/)[0]

Thank you

>Solution :

You can try this approach

  • flatMap is to collect all matched strings
  • filter is to get rid of empty results
const data =['{{Wanted Value}}', 'true', '{{Wanted Value}}', '{{Wanted Value}} unwanted {{Wanted Value}}', 'false']

const result = data.flatMap(stringData => stringData.match(/\{\{(.+?)\}\}/g)).filter(stringData => stringData);

console.log(result)
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