Search code examples
javascriptregexreplacegithub-flavored-markdown

Javascript replace all string not inside a markdown code block


I want to replace all occurrences of "](test" string with "test](new/test" in javascript but not inside a markdown code block

Example:

replace this one ![](test/asdsa.png)


```md
don't replace this
![](test/image1.png)
```

replace this ![](test/asdsasdsds.png)

```
don't replace this
console.log("![](test/blabla.png)");
const testStr = `![](test/image3.gif)`;
```

Solution

  • Split the string into array of lines and use a flag to track markdown blocks by checking if line starts with backticks

    Map the lines array and then join() to string with \n separator

    const textReplace = (str, subStr, newSubStr) => {
      let mdBlock = false;
    
      return str.split('\n').map(str => {
        if (str.trim().startsWith('```')) {
          mdBlock = !mdBlock;
        }
        // return unchanged string inside blocks, or run replace on string
        return mdBlock ? str : str.replace(subStr, newSubStr)
      }).join('\n');
    };
    
    
    const el = document.querySelector('textarea');
    el.value = textReplace(el.value, '](test' ,'---REPLACED---' )
    <textarea style="width:100%; height:250px">
    replace this one ![](test/asdsa.png)
    
    
    ```md
    don't replace this
    ![](test/image1.png)
    ```
    
    replace this ![](test/asdsasdsds.png)
    
    ```
    don't replace this
    console.log("![](test/blabla.png)");
    const testStr = `![](test/image3.gif)`;
    ```
    </textarea>