askmike
askmike

Reputation: 1970

How to change image urls in a markdown string

I am working on a nodejs CMS where users write blog posts in Markdown locally, after uploading we process the post in an HTML file. Sometimes users will add a picture like my dog.jpg to the post by copying the image and writing:

![a picture of my dog](my dog.jpg)

I use uslug to convert all filenames so that my dog.jpg becomes my-dog.jpg. However I also need to update the link in the blogpost using uslug, because a) otherwise the link would break because we just changed the filename and b) because most markdown parsers for node will skip the above image syntax because of the whitespace (while the image does get previewed in a lot of local Markdown editors, like Mou).

Does anybody know how I can achieve this using regex?

Upvotes: 4

Views: 2963

Answers (1)

Hubert OG
Hubert OG

Reputation: 19544

You'll need a lot of slashes:

string.replace(/(!\[.*?\]\()(.+?)(\))/g, function(whole, a, b, c) {
    return a + addDashesOrWhatever(b) + c;
});

Upvotes: 13

Related Questions