简体   繁体   中英

javascript regex strip out beginning and end part around JSON looking string

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

/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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM