Skip to content

Instantly share code, notes, and snippets.

@alash3al
Forked from orangexception/gist:1301150
Created December 31, 2015 04:08
Show Gist options
  • Save alash3al/d1513cdc6d6d6f690295 to your computer and use it in GitHub Desktop.
Save alash3al/d1513cdc6d6d6f690295 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/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment