Last active
July 29, 2021 08:35
-
-
Save loilo/f689c8be89d5628109aebee515b63555 to your computer and use it in GitHub Desktop.
Serialize console.log() arguments into a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function serializeConsoleLog(...args) { | |
let result = [] | |
// Format if first argument is a string | |
if (typeof args[0] === 'string') { | |
let formattedMessage = args.shift().replace(/%[csdifoO]/g, (match) => { | |
// Keep raw token if no substitution args left | |
if (args.length === 0) return match | |
switch (match) { | |
// Formatting (omitted) | |
case '%c': | |
args.shift() | |
return '' | |
// String | |
case '%s': | |
return String(args.shift()) | |
// Integer | |
case '%d': | |
case '%i': | |
return parseInt(args.shift()) | |
// Float | |
case '%f': | |
return parseFloat(args.shift()) | |
// Object | |
case '%o': | |
case '%O': | |
return JSON.stringify(args.shift()) | |
} | |
// Keep raw token if not replaced | |
return match | |
}) | |
if (formattedMessage.length > 0) { | |
result.push(formattedMessage) | |
} | |
} | |
// Serialize remaining arguments | |
let formattedArgs = args.map((arg) => | |
typeof arg === 'string' ? arg : JSON.stringify(arg) | |
) | |
result.push(...formattedArgs) | |
return result.join(' ') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment