Is there a specific regex pattern available to identify CSS and JavaScript links within an HTML file?

Currently, I am using a straightforward gulp task to compress my CSS and JS files. The task appends a .min extension to the names of the compacted files. Now, I want to make changes in the HTML to direct to these new compressed files, like so:

Replace this:

<link ...  href="...some_name.css ..." ...>

With this:

<link ...  href="...some_name.min.css ..." ...>

I have integrated the gulp-string-replace plugin, but I am struggling to come up with the correct regex pattern to target the JS and CSS links. It is not feasible for me to statically assign filenames or simply search for the strings .css or .js.

Some example tasks:

var replace = require('gulp-string-replace');

gulp.task('replace_1', function() {
  gulp.src(["./config.js"]) // Any file globs are supported
    .pipe(replace(new RegExp('@env@', 'g'), 'production'))
    .pipe(gulp.dest('./build/config.js'))
});

gulp.task('replace_2', function() {
  gulp.src(["./index.html"])
    .pipe(replace(/version(={1})/g, '$1v0.2.2'))
    .pipe(gulp.dest('./build/index.html'))
});

gulp.task('replace_3', function() {
  gulp.src(["./config.js"])
    .pipe(replace(/foo/g, function () {
        return 'bar';
    }))
    .pipe(gulp.dest('./build/config.js'))
});

Answer №1

Here's the solution to your query, which will address your issue and update all CSS file links.

replace(/href=\"(\S*)\.css\"/gi, 'href="$1.min.css"')

Answer №2

If you're looking to streamline this process, one effective approach is to utilize a tool like the gulp-processhtml plugin within your workflow. This plugin is specifically tailored to handle tasks similar to what you're trying to accomplish.

  <!-- build:css style.min.css -->
  <link rel="stylesheet" href="css/style.css">
  <!-- /build -->

The above snippet can be simplified to

<link rel="stylesheet" href="style.min.css">

I have included below a Gulp 4.0 task that I personally rely on for transferring a development version of HTML to a deployment directory:

var stripComments = require("gulp-strip-comments");
var modifyHTMLlinks = require("gulp-processhtml");
var addVersionString = require("gulp-version-number");
var print = require('gulp-print').default;

function processHTML() {
  return gulp.src(paths.html.src)
    .pipe(print())

    // modifyHTMLlinks: remove browserSync script link
    // update css/js links to .min.css or .min.js
    .pipe(modifyHTMLlinks())

    .pipe(stripComments.html(stripOptions))

    // add ?v=dateTime stamp to css and js links
    .pipe(addVersionString(versionConfig))
    .pipe(gulp.dest(paths.html.deploy));
}

Using such a method appears to offer more reliability compared to manipulating regex patterns manually. However, if you have any reservations about incorporating a plugin like this, feel free to share your concerns.

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

Creating a navbar that sticks to the top of the page

I've been working on some code to create a sticky navbar that remains fixed as I scroll down, but unfortunately, it's not working. I suspect the issue might lie in the CSS, as the HTML and javascript seem fine. Interestingly, this same code has w ...

Select the final word and enclose it within a span class

I have a task where I need to identify the last word in a class and then enclose it with a span element so that I can style it using JavaScript. <h1 class="title>A long tile</h1> <h2 class="title>A long tile</h2> should b ...

Utilizing withRouter outside a component to navigate through historical data

I'm still getting the hang of react router and encountering some challenges. I can easily use history within a component without any issues. However, when trying to access history from a function outside the component, I run into problems. Despite my ...

retrieve information at varying intervals through ajax

In my web page, there are two div elements that both fetch server data using AJAX. However, div-a retrieves data every second while div-b retrieves data every minute. How can I adjust the frequency at which each div fetches server data? ...

Is there a way to make images load only when the navigation buttons are clicked in a scrollable (jquery tools) rather than loading all images at once?

I came across this great demo tutorial that I'm currently following: The issue with the tutorial is that it loads all the images at once, which significantly impacts performance. My goal is to have it load a set of images each time you click the arro ...

Assistance needed for iterating through JSON data

I need assistance retrieving specific data from a JSON response in my JavaScript code. Unfortunately, the current approach is not providing the desired results: This is my JavaScript code snippet: function retrieveArtists(response){ var artistList ...

Deciphering the Syntax of React Functional Components

Seeking guidance as a ReactJS novice working through the react docs. I've hit a snag trying to understand and implement an example provided in the documentation. Can anyone please lend a hand in helping me spot my mistake?https://i.sstatic.net/DwlXp.p ...

gulp-webpack is unable to locate node packages

Currently working on developing a modern Angular application. I have opted to use gulp-webpack for quick development builds. To handle my TypeScript bundling and node modules dependencies, I am relying on webpack. However, it seems that gulp-webpack is no ...

"Commitment made ahead of time without allowing for the outcome to

I'm completely new to working with promises and I'm encountering some unexpected behavior in my code. The issue lies in the TaskRunner.SyncObjects function within Main.js, which should be waiting for the selectedCourses variable to be populated ...

Phonegap experiencing issues with executing JavaScript code

My attempt to utilize phonegap is encountering an issue where my javascript is not running. Here's what I've tried so far: <html> <head> <meta charset="utf-8" /> <meta name="format-detection" content="telephone=no" / ...

Using a javascript parameter in a cshtml file to filter data in a datatable

Here is the model code public class viewCase { public List<string> lstCategory { get; set; } public DataTable dtWrkTsk { get; set; } } This is the controller code string query = "SELECT WorkFlowID,Subject,Category FROM CMSTasksWorkFlow" ob ...

Using Node.js to alter an existing JSON file

I have a file named a1.json that contains the following data: { "Key1" : [ { "Key11" : "Value11" , "Key12" : "Value12" }, { "Key21" : "Value21" , "Key22" ...

Interact with Dialogflow using fulfillment to retrieve responses by opening an HTTP URL

Despite my efforts, I have yet to find a satisfactory solution. I am in the process of creating an agent on Dialogflow. This agent will be embedded on a webpage, not as part of Facebook Messenger or Google Assistant. The purpose of this agent is to guide ...

Discovering the specific value from a fixture file in Cypress

When I receive a JSON Response, how can I extract the "id" value based on a Username search? For instance, how can I retrieve the response with an "id" value of 1 when searching for the name "Leanne Graham"? It is important to note that the response valu ...

What is the best way to connect or link to a HTML table row <tr>

Is there a way to trigger an alert when the user double clicks on the whole row? ...

Reverse the action and postpone the Ajax call for a specified time or until the next action occurs

How can I implement a setup and undo feature for my ajax calls that allows users to delay the call for a set amount of time and abort it if needed? I also want to be able to stop the delay and proceed with the most recent ajax call if another action is tri ...

Transforming JSON data into comma-delimited values (with thousands separators) using Angular 5 and ES6 syntax

Is there a more elegant method to convert a JSON response into comma-separated numbers for displaying currency purposes? Here is the code I have currently: let data = { "business":{ "trasactionTableData":[ { ...

Tips for saving the recently assigned IP address from Terraform?

My current project involves cloud provisioning with Terraform on an EC2 instance, where the process is automated to begin when a request is sent from the front end to the back end. In the backend, I am using Node.js and implementing shell scripts to execu ...

Encountering a missing value within an array

Within my default JSON file, I have the following structure: { "_name":"__tableframe__top", "_use-attribute-sets":"common.border__top", "__prefix":"xsl" } My goal is to add values by creating an array, but I am encountering an issue where my ...

Managing state with Apollo within a component

Greetings and thank you for taking the time to help me out. I am currently diving into the world of Apollo and React, but it seems like I am struggling with some logic here. On my main page index.js, I have initialized Apollo in the following way: export c ...