Regex only match specific whitespaces

I have some text that i would like to shrink with regular expressions. My goal is to turn this:

function mFunct(variable){
var a, b, c;
new Class();
}

into this:

function mFunct(variable){var a,b,c;new Class();}

I tried this:

(?:(new|var|function)\s)|\s

but it selects var a. How can I change it so that it doesn't?

1 answer

  • answered 2018-09-21 22:00 Félix Gagnon-Grenier

    You can use the negative lookbehind to ensure matching only whitespace that is not preceeded by the keywords:

    (?<!function|var|new)\s
    

    See here. We can't see the newlines being highlighted, them having no width and all, but in the list on the right you see the characters being matched. Removing all those matched characters should give the desired output.