console-log-formatting.html   [plain text]


<script>
    var s = "this is a string";
    var i = 5;
    var ni = -5;
    var f = 3.14159;
    var o = { prop1: 1, prop2: 2 };
    var specifiers = {
        s: "string",
        i: "integer",
        d: "integer",
        f: "float",
        "0.3f": "float with precision",
        o: "object",
        z: "unsupported",
    };

    function test(args) {
        var functions = ["log", "debug"];
        for (var i = 0; i < functions.length; ++i) {
            console.info("console." + functions[i] + "(%s)", args);
            try {
                eval("console." + functions[i] + "(" + args + ")");
            } catch (e) {
                console.error(e);
            }
        }
    }

    function testAllSpecifiers(value, description) {
        for (var specifier in specifiers)
            test("'Format " + description + " as " + specifiers[specifier] + ": %" + specifier + "', " + value + "");
    }

    function runTests() {
        var values = [
            { value: "window.noSuchVariable", description: "undefined" },
            { value: "s", description: "string" },
            { value: "i", description: "positive integer" },
            { value: "ni", description: "negative integer" },
            { value: "f", description: "float" },
            { value: "o", description: "object" },
            { value: "document.body", description: "body" },
            { value: "/test/", description: "RegExp" },
            { value: "true", description: "boolean" },
            { value: "null", description: "null" },
        ];

        for (var i = 0; i < values.length; ++i)
            testAllSpecifiers(values[i].value, values[i].description);

        var tests = [
            "'simple test'",
            "'multiple', 'parameters', 'should', 'be', 'concatenated'",
            "document",
            "document, document.body, window, window.location",
            "document, document.body, 'hello', 'goodbye', window.location",
            "'Format string with fewer specifiers than parameters: %o %i %f', document.body, i, f, ni, o",
            "'Format string with more specifiers than parameters: %o %i %f %i %o', document.body, i, f",
        ];

        for (var i = 0; i < tests.length; ++i)
            test(tests[i]);

    }
</script>
<p>Test for <a href="https://bugs.webkit.org/show_bug.cgi?id=17228">Bug 17228: console.{log,warn,info,error} should support format strings, variable arguments</a>.</p>
<p>Open the Inspector (right-click and choose "Inspect Element"), then click the "Run Tests" button.</p>
<button onclick="runTests()">Run Tests</button>