I have a some Javascript which creates and maintains a string of CSS, for example:
".joe{top:1rem} @media(min-width: 64rem){ .blogs{top:3rem} }"
Part of the logic can add a new CSS rule inside a @media query. Currently, it adds the rule after the opening { bracket of the @media query, because it's quite easy to search for @media(min-width: 64rem){ and then insert at that index, for example:
".joe{top:1rem} @media(min-width: 64rem){ .new{top:3rem} .blogs{top:3rem} }"
Here's a snippet of the logic:
// find the existing media query from the style tag
// styleTagCache is the CSS string being maintained
const searchString = `@media(min-width:${breakpoint}){`;
const mqIndex = styleTagCache.indexOf(searchString) + searchString.length;
// insert rule into the media query
const styleTagArray = [...styleTagCache];
styleTagArray.splice(mqIndex, 0, ruleString);
styleTagCache = styleTagArray.join('');
However, I'd like to insert the new rule at the end of the media query, before its closing } bracket, like this:
".joe{top:1rem} @media(min-width: 64rem){ .blogs{top:3rem} .new{top:3rem} }"
I've had a few futile attempts, but can't figure it out. The difficult part seems to be searching for the media query's closing }, but ignoring any other } which are part of the CSS rules inside it.