Colors in JavaScript console

前端 未结 27 2222
说谎
说谎 2020-11-22 11:42

Can Chrome\'s built-in JavaScript console display colors?

I want errors in red, warnings in orange and console.log\'s in green. Is that possible?

27条回答
  •  醉酒成梦
    2020-11-22 12:25

    I recently wanted to solve for a similar issue and constructed a small function to color only keywords i cared about which were easily identifiable by surrounding curly braces {keyword}.

    This worked like a charm:

    var text = 'some text with some {special} formatting on this {keyword} and this {keyword}'
    var splitText = text.split(' ');
    var cssRules = [];
    var styledText = '';
    _.each(splitText, (split) => {
        if (/^\{/.test(split)) {
            cssRules.push('color:blue');
        } else {
            cssRules.push('color:inherit')
        }
        styledText += `%c${split} `
    });
    console.log(styledText , ...cssRules)
    

    technically you could swap out the if statement with a switch/case statement to allow multiple stylings for different reasons

提交回复
热议问题