1

I'm trying to replace a link in a html file with regex and nodejs. I want to replace links without a .min.js extension.

For example, it should match "common.js" but not "common.min.js"

Here's what I've tried:

let htmlOutput = html.replace(/common\.(?!min)*js/g, common.name);

I think this negative lookahead should work but it doesn't match anything. Any help would be appreciated.

Ian Gleeson
  • 383
  • 3
  • 17

3 Answers3

2

The (?!min)*js part is corrupt: you should not quantify zero-width assertions like lookaheads (they do not consume text so quantifiers after them are treated either as user errors or are ignored). Since js does not start with min this lookahead even without a quantifier is redundant.

If you want to match a string with a whole word common, then having any chars and ending with .js but not .min.js you need

/\bcommon\b(?!.*\.min\.js$).*\.js$/

See the regex demo.

Details:

  • \b - word boundary
  • common - a substring
  • \b - word boundary
  • (?!.*\.min\.js$) - immediately to the right, there should not be any 0 or more chars followed with .min.js at the end of the string
  • .* - any 0 or more chars
  • \.js - a .js substring
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

Here, we likely can find a simple expression to pass any char except new lines and ., after the word common, followed by .js:

common([^\.]+)?\.js

Demo

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 27,428
  • 11
  • 44
  • 69
0

The end regex I'm using is /\bcommon[^min]+js\b/g

This will find the word common with any amount of chracters afterword except if those characters contain the word minand ending in js allowing me to replace scripts on my html page like:

script src="~/dist/common.js"

OR

script src="~/dist/common.9cf5748e0e7fc2928a07.js"

Thanks to Wiktor Stribiżew for helping me.

Ian Gleeson
  • 383
  • 3
  • 17
  • You are rather wrong. `\bcommon[^min]+js\b` matches `common` followed with 1 or more chars other than `m`, `i`, `n` followed with `js` substring. So you need `\bcommon(?:(?!min).)*?js\b` I guess, judging by your description. Or `\bcommon\b(?!\S*\.min\.js\b)\S*\.js\b` – Wiktor Stribiżew Jun 05 '19 at 16:37