Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active July 29, 2021 08:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loilo/f689c8be89d5628109aebee515b63555 to your computer and use it in GitHub Desktop.
Save loilo/f689c8be89d5628109aebee515b63555 to your computer and use it in GitHub Desktop.
Serialize console.log() arguments into a string
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