⚠ Created by AI 🤖
When scraping React Server Components (RSC) data or serialized script tags from the DOM, you often encounter weirdly escaped string patterns like push([1,"15:{\\\"@context\\\":...}\\n"]).
Here is a quick guide on how to extract, fix the regex, and decode these nested payloads efficiently.
1. The Regex Pitfall
When writing a regular expression to match literal string structures like push([1,...]), characters like (, ), [, and ] must be escaped with a backslash because they are regex special characters.
Additionally, if the string ends with a literal \n character text (rather than a physical line break), you must use a double backslash \\n.
Correct Regex:
const regex = /push\(\[1,\"15\:(.+)\\n\"\]\)/;
2. Why JSON.stringify Cannot Escape Regex
You cannot use JSON.stringify() to escape a regular expression. JSON.stringify only formats strings and objects to comply with the JSON specification. It leaves structural regex tokens like parentheses and brackets untouched.
To dynamically escape strings for a regex constructor, use a dedicated replacer function:
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
3. The Cleanest Way to Decode the Payload
Instead of using regex capture groups combined with a string interpolation hack like JSON.parse(JSON.parse(\"${match[1]}"`)), it is safer and cleaner to grab the whole array structure and let JSON.parse` natively unescape the string layers.
Here is the ultimate simplified snippet to extract and decode the payload out of a document:
// 1. Locate the raw array bounds in the DOM
const html = document.documentElement.outerHTML;
const startIdx = html.indexOf('[1,"15:');
const endIdx = html.indexOf('"])', startIdx) + 2;
if (startIdx !== -1 && endIdx !== -1) {
// 2. Parse the outer JSON structure safely
const rawArrayStr = html.substring(startIdx, endIdx);
const [_, dataString] = JSON.parse(rawArrayStr);
// 3. Strip the '15:' prefix and trailing newline text, then parse the inner object
const cleanJsonStr = dataString.replace(/^15:/, '').replace(/\n$/, '');
const finalObject = JSON.parse(cleanJsonStr);
console.log(finalObject); // Clean, fully interactive JS Object
}
Or
// 1. Match the entire array string instead of capturing parts
const match = document.documentElement.outerHTML.match(/\[1,\"15\:.+?\\n\"\]/);
// 2. Parse it directly into a clean JS Array, then extract the inner JSON string
const innerJson = match ? JSON.parse(match[0])[1].split('15:')[1].replace(/\n$/, '') : null;
const finalObj = innerJson ? JSON.parse(innerJson) : null;
Or
const match = document.documentElement.outerHTML.match(/push\(\[1,\"15\:(.+)\\n\"\]\)/);
const finalObj =JSON.parse(JSON.parse(`"${match[1]}"`))
Key Takeaways
- Double
JSON.parse()is a legitimate strategy when dealing with nested, serialized JSON-in-JSON strings. - Parsing the outer container format first automatically resolves the initial layer of backslash escaping natively.