JAVASCRIPT

Parse Custom Log-like Strings with Regex Capture Groups

Learn to extract specific data fields like timestamp, level, and message from custom log or structured strings using regular expression capture groups in JavaScript.

function parseLogEntry(logEntry) {
  // Example log format: [INFO] 2023-10-27T10:30:00Z - User login successful for 'john.doe'.
  // Regex captures: [level] [timestamp] - [message]
  const logRegex = /^\[(INFO|WARN|ERROR|DEBUG)\]\s(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z)\s-\s(.+)$/;
  const match = logEntry.match(logRegex);

  if (match) {
    // Access captured groups by index
    return {
      level: match[1],
      timestamp: match[2],
      message: match[3]
    };
  }
  return null;
}

// Examples:
// const entry1 = "[INFO] 2023-10-27T10:30:00Z - User login successful for 'john.doe'.";
// console.log(parseLogEntry(entry1));
/* Output:
// {
//   level: "INFO",
//   timestamp: "2023-10-27T10:30:00Z",
//   message: "User login successful for 'john.doe'."
// }
*/
// const entry2 = "[WARN] 2023-10-27T10:35:15Z - Disk space low on /dev/sda1.";
// console.log(parseLogEntry(entry2));
// const entry3 = "Invalid log format entry.";
// console.log(parseLogEntry(entry3)); // null
How it works: This JavaScript function uses a regular expression with multiple capture groups to parse a custom-formatted log string. It efficiently extracts discrete fields such as the log level, timestamp, and the actual message content, returning them as a structured object for convenient access and processing of textual data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs