Using regular expressions to substitute relative image URLs in a Markdown string with JavaScript/Node

I am currently working on a project where I need to update the image URLs in some markdown posts pulled from a GitHub repository. The images are all relatively linked, and I want to prepend them with a CDN link globally.

Current: [000](images/000.png)

Desired:

[000](https://cdn.jsdelivr.net/gh/gaurangrshah/site-cms@main/images/000.png)

I have tried a few methods, but I can't seem to target the "image" for some reason:

post.matter.content = post?.matter?.content.replace( ""images.*\/g"", ${imageBase}/images );

Answer №1

When using the String.replace method, you have the option to pass either a string or a regular expression as the first argument. In your case, you are currently passing a string, but what you actually need is a regular expression. To correct this issue, simply update the first parameter of the replace method like so:

const post = {
  matter: {
    content: `[000](images/000.png)`
  }
};

const imageBase = "https://cdn.jsdelivr.net/gh/gaurangrshah/site-cms@main";

post.matter.content = post?.matter?.content.replace(
  /images/g,
  `${imageBase}/images`
);

console.log(post.matter.content);

Answer №2

Here is a clever non-regex approach that I found and wanted to document for my future reference.

post.matter.content = post?.matter?.content.replaceAll('images', `${imageBase}/images`);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method for capturing an image of a highcharts chart in node.js?

Utilizing the capabilities of Highcharts, we have a handy built-in feature for downloading current charts in various formats (example: http://www.highcharts.com/demo/, look for the download button indicated by an arrow icon). Options include saving the cha ...

CSS Only Sidebar Dropdown (without using Bootstrap)

I want to create a sidebar with collapsible dropdown options and smooth animations using only pure css/js/html/jquery, without relying on bootstrap like I did in the past. Here is an example of what I created previously with bootstrap: Now, as a challenge ...

JavaScript code to verify if a checkbox is selected

Having some trouble making a text box value change based on checkbox status. I've attached a function to the onclick event of the checkbox, but it's not quite working as expected. <div> MyCheckbox <input type="checkbox" id="Check1" name ...

In Node.js, use the `[]` operator to select elements from an array of strings without including

In my situation, I am working with an array of strings which can sometimes be an array containing only one string. The issue is that when this happens, using array[0] to retrieve the value does not return the entire string but rather just the first charact ...

What is the method for activating a hook after a state change in a functional component?

I'm currently working on a custom pagination hook that interacts with an API to fetch data similar to React Query. The concept is straightforward. I aim to invoke this hook whenever a specific state (referred to as cursor) undergoes a change. Below i ...

Navigating through parent folder HTML files from child folder HTML files

Seeking guidance as I embark on a new project! Check out this link to see my skills in action: collegewebsite.zip Now for the query at hand. I am working on a project named Coffee Cafe for my tuition assignment. It involves utilizing CSS and HTML with J ...

Utilizing ThreeJS: Implementing a Sprite in Conjunction with the OculusRiftEffect

I am currently working on a project for the OculusRift using the OculusRiftEffect found at https://github.com/mrdoob/three.js/blob/master/examples/js/effects/OculusRiftEffect.js and incorporating Sprites into the design. However, I am facing an issue where ...

Several virtual hosts functioning properly on Chrome, yet encountering issues on Firefox and Safari

I am utilizing the express and vhost packages to configure multiple servers on a single port, each with a distinct subdomain. Each server corresponds to a specific directory in my local file system and is responsible for serving static files. ~/repos/serv ...

Tips for finding data attribute in Select2?

Is it possible to search for items based on both the value and data-test attribute in select2? <option value="Test 1" data-test="user-1">Test 1</option> <option value="Test 2" data-test="user-2">T ...

Transfer an array from XML to PHP into JavaScript in order to deactivate specific dates within a datepicker using the beforeShowDay function

My process involves reaching out to another website through a GET request and receiving XML data for interpretation. Here is how I make the contact: $v= file_get_contents( "https://www.v.com/fechasexcursion.php? agent=M&password=s&fec ...

Challenges with loading times in Angular.js(SPA) applications

My website is created using Angular.js and I've been facing challenges with slow loading times, particularly for users in regions with slower internet speeds. In some cases, the page doesn't load at all. What steps can I take to enhance the initi ...

A guide to accessing REST services in AngularJS using basic authentication

I currently have a REST service up and running on my server. Using Chrome Postman, I am able to access this service with Basic Authentication. However, I now want to build a user interface in AngularJS to display the data received from the REST service. T ...

What is the reason for function components running in multiples of 2 when the state changes?

I need help with a React question that I can't quite figure out. I have a component where new data keeps getting added to the existing data. Initially, it makes sense for two console logs to appear due to Mount and Update. But after that, why do 4 con ...

Looking for a way to keep responses on the same page with a Node.js, Express, MongoDB stack?

I recently created a one-page application using Node and Express. This page consists of multiple sections, each containing a form. I am currently posting the data from these forms to Mongo, but I am looking for a way to receive a response on the same page ...

How can I extract and print only the desired div content and send it via email from an HTML/JS page?

Is there a way to print only specific content within a div, rather than the entire webpage in JS/HTML? Below is the code snippet I am using: function displayRadioValue() { let section1 = document.querySelectorAll('.section-1 > input[type="ra ...

Using AngularJS Typeahead with restrictions on $http requests

I have been attempting to restrict the number of results displayed by Angular Bootstrap Typeahead during Async calls, but unfortunately, it does not seem to be functioning as expected. <input type="text" ng-model="asyncSelected" placeholder="Locations ...

Guide to updating a div's content with Ajax for a refreshing experience

I typically use jQuery's load function to bring content from page A into page B. However, loading a div's content into itself just to refresh it seems unnecessary. Is there a better solution for this issue? $('#A').load('pageX.php ...

"Difficulty encountered in getting scroll-x: auto to function properly in iOS and Safari when embedding an image with a click map inside a container

We're encountering an issue with a wide image (a colour palette) that is too large for mobile screens, so we decided to place the image in a container with a horizontal scroll bar. This solution works perfectly on most browsers, but not on iOS and Saf ...

What could be causing the CSS file to not be recognized in server.js?

My Node.js server is functioning properly, but I have recently noticed that my CSS files are not being served through the server. Upon inspecting the elements and checking the sources tab, I can see that the CSS file is present, but it is not being read ...

Steps for sending the form after completing validation

I have implemented a beautiful form with jQuery validation, but I'm unsure of where to place the function that should execute after the form has been validated. Below is the structure of the form: <form id="myForm" class="needs-vali ...