Read JavaScript variables from a file with Python
javascript, python
Solution
Assuming you only want the two lines, and they are at the top of the file...
import re
js = open("yourfile.js", "r").readlines()[:2]
matcher_rex = re.compile(r'^var\s+(?P<varname>\w+)\s+=\s+"(?P<varvalue>[\w\s]+)";?$')
for line in js:
matches = matcher_rex.match(line)
if matches:
name, value = matches.groups()
print name, value
Problem
I use some Python scripts on server-side to compile JavaScript files to one file and also add information about these files into database. For adding the information about the scripts I now have yaml file for each js file with some info inside it looking like this: ``` title: Script title alias: script_alias ``` I would like to throw away yaml that looks redundant here to me if I can read these variables directly from JavaScript that I could place in the very beginning of the file like this: ``` var title = "Script title"; var alias = "script_alias"; ``` Is it possible to read these variables with Python easily?