Search code examples
regexlookbehind

js regex replace match in certain paragraph


---
title: test
date: 2018/10/17
description: some thing
---

I want to replace what's behind date if it's between ---, in this case 2018/10/17. How to do that with regex in JS?

So far I've tried;

/(?<=---\n)[\s\S]*date.+(?=\n)/ 

but it only works when date is the first line after ---


Solution

  • I'm not sure Javascript supports look behind at all, but if your environment supports it, you can try this regex:

    /(?<=---[\s\S]+)(?<=date: )[\d/]+(?=[\s\S]+---)/
    

    It looks behind for '---' followed by anything, then it looks behind for 'date: ' before it matches digits or slash one or more times, followed by a look ahead for anything followed by '---'.

    Now you can easily replace the match with a new date.