CodexBloom - Programming Q&A Platform

Regex to Extract Key-Value Pairs from JSON-like Strings in JavaScript - implementing Extra Commas

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-26
regex javascript json JavaScript

I'm testing a new approach and I'm trying to use regex to extract key-value pairs from a JSON-like string in JavaScript, but I'm running into issues when there are extra commas at the end of the pairs... For example, I have the string: ```javascript const input = '{"name":"John", "age":30, "city":"New York",}'; ``` I want to extract the pairs like `name: John`, `age: 30`, and `city: New York` without getting exploring due to the trailing comma after the last pair. I initially tried the following regex: ```javascript const regex = /"(.*?)":"(.*?)"/g; ``` However, this fails to match because of the trailing comma, and I get no results. I also attempted to modify my regex to: ```javascript const regex = /"(.*?)":"(.*?)"(,)?/g; ``` But this still doesn't yield any matches. I need to capture the key-value pairs correctly and handle cases where commas occur at the end of the string. Is there a better approach or regex pattern I should use? I'm currently using Node.js version 14.17.0 and would appreciate any guidance on how to properly extract these pairs without running into issues with invalid JSON structures. Has anyone else encountered this? This is part of a larger REST API I'm building. Any ideas what could be causing this? This issue appeared after updating to Javascript 3.10. Is there a better approach?