Find Section In String But Replace Whole Case Regex?

- 1 answer

Let's say I have a file's contents as a string:

@import '/app/a';
@import '/app/b.development';

I need to match the import statement that has the word 'development' in it. If it does find it, I need to remove the whole statement, so it would then return:

@import '/app/a';

So my question is how can I match the whole import statement after I detect it has the word 'development'?

I've managed to match the 'development' string and replace that, but not the whole statement.


var string = "@import '/app/a'; @import '/app/b.development';";
var output = string.replace(/(development)/g, '');

document.body.innerHTML = output;
// outputs @import '/app/a'; @import '/app/b.';
// I want to output @import '/app/a';




You could use the following regular expression:


Replace any matches with the first capturing group:

string.replace(/[^;]*development[^;]*;|([^;]+;)/g, '$1');


  • [^;]*development[^;]*; - Match one or more non ; characters followed by the string 'development', followed by one or more non ; characters followed by a ;.
  • | - Alternation to match [^;]*development[^;]*; or ([^;]+;).
  • ([^;]+;) - Capturing group to match one or more non ; characters followed by a ;.

This expression essentially matches all import statements, but then negates each import statement that contains the string 'development' by not capturing it in a capturing group.

This results in the import statements with the string of 'development' being removed since they are replaced with an empty capturing group.

var string = "@import '/app/a'; @import '/app/b.development';@import '/test/';";
var output = string.replace(/[^;]*development[^;]*;|([^;]+;)/g, '$1');

document.body.textContent = output;