-2

Using Typescript and Node v8, I am trying to process a markdown text and remove all the image URLs that follow a specific pattern:

  • URLs that contain the word forbidden
  • URLs with IP addresses

I am trying using this regular expression:

![([^]]+)]((.(fordbidden|(?:[0-9]{1,3}.){3}[0-9]{1,3}).)\

This typescript code:

const markdownText =
            '\
            * ![Allowed image](http://accepteddomain/image.png)\
            * ![Forbidden domain image](http://fordbidden/image.png) \
            * ![Forbiden IP image](http://80.11.20.15/image.png) \
            ';

const forbiddenImages = /!\[([^\]]+)\]\((.*(fordbidden|(?:[0-9]{1,3}\.){3}[0-9]{1,3}).*)\)/gm;

function removeForbidden(markdown: string): string {
    return  markdown.replace(forbiddenImages,"![$1] ()");
}

console.log(removeForbidden(markdownText)

I am getting only the first line of the input:

* ![Allowed image] ()           

Thanks in advance!

Alfredo
  • 139
  • 1
  • 2
  • 10

1 Answers1

1

It seems to me the issue come from the back slashes used inside the string. I have tried using ` and it's working:

const markdownText =
            `
            * ![Allowed image](http://accepteddomain/image.png)
            * ![Forbidden domain image](http://fordbidden/image.png) 
            * ![Forbiden IP image](http://80.11.20.15/image.png)
            `;

const forbiddenImages = /!\[([^\]]+)\]\((.*(fordbidden|(?:[0-9]{1,3}\.){3}[0-9]{1,3}).*)\)/gm;

function removeForbidden(markdown: string) {
    return  markdown.replace(forbiddenImages,"![$1] ()");
}

console.log(removeForbidden(markdownText))

`

Mika Andrianarijaona
  • 1,477
  • 14
  • 27