Skip to content

Instantly share code, notes, and snippets.

@orangexception
Created October 20, 2011 13:33
Show Gist options
  • Save orangexception/1301150 to your computer and use it in GitHub Desktop.
Save orangexception/1301150 to your computer and use it in GitHub Desktop.
Minify JavaScript Regular Expression

Notice

Do not run this against minified JavaScript packages. The minified packages often rely on line returns to execute correctly.

This regular expression was designed to minify simple JavaScript.

Regular Expression

(?s)[\t\r\n]|[ ][ ]+|/\*.*?\*/*

I put spaces in square brackets as a reminder that they exist. Spaces can be important. For example, $( "#foo #bar" ) should not become $("#foo#bar"). However, we do want to remove spaces if they are used for indentation.

I'm having trouble removing // comments due to values such as "http://." I'm having some success with (?s)(?m)[\t\r\n]|[ ][ ]+|/\*.*?\*/|^//[^\r\n]*|[^\\"":]//[^\r\n]*, but I need to build more test cases.

Usage in ColdFusion

sJavaScriptContent= sJavaScriptContent.ReplaceAll( "(?s)[\t\r\n]|[ ][ ]+|/\*.*?\*/**" , "" );

Test Cases

// Test 0
/* Test 1 */
/* Test * / * 2 */
/* Test
. test
. test

test 3
*/
/* Test * / * 4 */  /* Test 5 *//**/
/* Test 6 /*/
// Test 7
/* Test
// 8
*/
// ////// Test 9
// */ Test 10
  $( "#foo #bar" ).val( "Test 11 - This value should exist." );
    $( "#foo #bar" ).val( "http://orangexception.com/" ); // Test 12 - http:// should exist. However, this comment should not exist. //
// Test 13 - This line should be gone. http://orangexception.com/foo/bar/
@orangexception
Copy link
Author

I'd like to say this works in all cases, but it does not.

I'm adding a couple of more tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment