Rahul Bhooteshwar
Rahul Bhooteshwar

Reputation: 1955

Change Image source in Markdown text using Node JS

I have some markdown text containing image references but those are relative paths & I need to modify those to absolute paths using NodeJS script. Is there any way to achieve the same in simple way ?

Example:

Source

![](myImage.png?raw=true)

Result

![](www.example.com/myImage.png?raw=true)

I have multiple images in the markdwon content that I need to modify.

Upvotes: 2

Views: 674

Answers (2)

Charles Zhao
Charles Zhao

Reputation: 186

I ran into the same issue yesterday, and came up with this solution.

const markdownReplaced = markdown.replace(
  /(?<=\]\()(.+)(?=(\)))/g,
  (url) => `www.example.com/${url}`,
);

The regex finds anything starts with ]( and ends with ), without including the capturing group, which is the original URL itself.

Upvotes: 0

axm__
axm__

Reputation: 2673

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.

enter image description here

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.

Upvotes: 2

Related Questions