1

Im hoping someone might be able to help with this.

Ive got a text file on the server loaded with the following

var templateCache = '{"templateCache":[  {"test":"123"}  ]}';

as its a text file, we are opening it and are aiming to strip out

var templateCache = '----';

so we can convert the string into an object using JSON.stringify().

We are making use of Rhino.js as the server so we can only use vanilla JS functions to process this string into something usable for our app.

Back story

The file is included in the main function of our little app, but for us to manipulate this set of variables we are opening it, converting it into a JSON object and applying whats neccessary to it and then saving it back as the variable so it doesnt impact our app. but I cant figure out how to strip out the var templateCache = ''; and leave the middle content in place and im not sure what to look for via google to get the thing into order

1
  • Is the snippet above the entirety of the file? Commented May 12, 2017 at 23:10

1 Answer 1

2

/var templateCache = '(.+)';$/m

The regex feature you are looking for is called 'capturing'. It's normally implemented with () parentheses in most languages, js included.

What this example regex does is it 'captures' and remembers everything between the () parentheses and makes it available for more processing.

Here's a quick example for your case:

var fileContent = 'var templateCache = \'{"templateCache":[  {"test":"123"}  ]}\';'

var regex = /var templateCache = '(.+?)';$/m;
var matchedGroups = regex.exec(fileContent);

console.log('Result String: ' + matchedGroups[1]);
console.log(JSON.parse(matchedGroups[1]));

Edit: changed the regex to handle cases where the file has more '; substrings on the same line after the json part.

Sign up to request clarification or add additional context in comments.

1 Comment

Worth noting that this will only work if var templateCache = ...; is the only (semicolon-terminated) statement in your file. e.g. var templateCache = '{}'; somethingElse = 'single-quoted-string'; will not match correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.