Check this working example: https://repl.it/repls/BlackJuicyCommands
First of all you need the read the file with fs.readFile()
and parse the Buffer
to a string
.
Now you got access to the text of the file, you need the replace every image path with a new image path. One way to capture it is with a regular expression. You could for example look for ](ANY_IMAGE_PATH.ANY_IMAGE_EXTENSION
. We're only interested in replacing the ANY_IMAGE_PATH
part.
An example regex could be (this could be improved!) (see it live in action here: https://regex101.com/r/xRioBq/1):
const regex = /\]\((.+)(?=(\.(svg|gif|png|jpe?g)))/g
This will look for a literal ]
followed by a literal (
followed by any sequence (that's the .+
) until it finds a literal .
followed by either svg
, gif
,png
, or jpeg
/ jpg
. the g
after the regex is necessary to match all occurences, not only the first.
Javascript/node (< version 9) does not support lookbehind. I've used a regex that includes the ](
before the image path and then will filter it out later (or you could use a more complex regex).
The (.+)
captures the image path as a group. Then you can use the replace function of the string. The replace function accepts the regex as first argument. The second argument can be a function which receives as first argument the full match (in this case ](image_path_without_extension
and as the following arguments any captured group.

Change the url with the node modules path
or url
and return the captured group (underneath I've called that argument imagePath
). Because we're also replacing the ](
, that should be included in the return value.
const url = require('url');
const replacedText = data.toString().replace(regex, (fullResult, imagePath) => {
const newImagePath = url.resolve('http://www.example.org', imagePath)
return `](${newImagePath}`;
})
See the repl example to see it live in action. Note: in the repl example it is written to a different file. Use the same file name if you want to overwrite.