JavaScript / ECMAScript

Logfmt Key-Value Pair in JS

Parse key=value pairs from logfmt-style log lines, supporting both quoted and unquoted values.

Try it in the JS tester →

Pattern

regexJS
([a-zA-Z_][\w.]*)=("[^"]*"|\S+)   (flags: g)

JavaScript / ECMAScript code

jsJavaScript
const re = new RegExp("([a-zA-Z_][\\w.]*)=(\"[^\"]*\"|\\S+)", "g");
const input = "level=info msg=\"user logged in\" user_id=42";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));

Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).

How the pattern works

([a-zA-Z_][\w.]*) captures the key: starts with a letter or underscore, followed by word chars or dots. = is a literal separator. ("[^"]*"|\S+) captures the value: either a double-quoted string (allowing spaces inside) or an unquoted sequence of non-whitespace characters.

Examples

Input

level=info msg="user logged in" user_id=42

Matches

  • level=info
  • msg="user logged in"
  • user_id=42

Input

ts=2024-01-15T14:30:00Z status=200 latency=12ms

Matches

  • ts=2024-01-15T14:30:00Z
  • status=200
  • latency=12ms

Same pattern, other engines

← Back to Logfmt Key-Value Pair overview (all engines)