Stripping JavaScript Function Declarations in Java Using Regular Expressions

Extracting or removing JavaScript function blocks from mixed text strings requires precise pattern matching. JavaScript functions typically follow the syntax function name(params) { ... body ... }. A standard regex can target this structure, though multiline support and dotall consumption require careful configuration of the regex engine.

The following Java utility demonstrates how to locate and remove these function signatures from a raw text payload. The implementation leverages java.util.regex.Pattern with flags enabled for mlutiline processnig to capture block bodies effectively.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class JsFilterUtil {
    private static final Pattern JS_FUNCTION_PATTERN = 
        Pattern.compile("(?m)\\s*function\\s+[a-zA-Z_$]+\\s*\\([^)]*\\)\\s*\\{[\\s\\S]*?\\}", Pattern.CASE_INSENSITIVE);

    public static String removeFunctionBlocks(String sourceText) {
        if (sourceText == null || sourceText.isEmpty()) {
            return sourceText;
        }
        
        Matcher matcher = JS_FUNCTION_PATTERN.matcher(sourceText);
        StringBuffer replacementBuffer = new StringBuffer();
        
        while (matcher.find()) {
            matcher.appendReplacement(replacementBuffer, "");
        }
        matcher.appendTail(replacementBuffer);
        
        return replacementBuffer.toString().trim();
    }

    public static void main(String[] arguments) {
        String rawData = """
            function calculateTotal(items, tax) {
                let subtotal = items.reduce((sum, item) => sum + item.price, 0);
                return subtotal * (1 + tax);
            }
            
            function formatCurrency(amount) {
                return "$" + amount.toFixed(2);
            }
            
            console.log("Script execution started");
            """;

        System.out.println(removeFunctionBlocks(rawData));
    }
}

Executing this routine against a composite script preserves all non-declaration statements. The resulting string contains only the residual logic and console outputs, effectively isolating the procedural blocks from the surrounding data.

Tags: java javascript regex string-processing text-filtering

Posted on Wed, 28 Oct 2026 16:10:52 +0000 by Liquid Fire