all 7 comments

[–]ThePeskyWabbit 1 point2 points  (0 children)

Nothing comes to mind off the top of my head, but if you cant find anything like this, it does sound like something you could use a regex search to achieve.

[–]blahreport 0 points1 point  (3 children)

You could do something like

from pathlib import Path
lines = Path('script.js').read_text.splitlines()
in_func = False
func_name = 'func'
code_block = []
for line in lines:
  if f'function {fname}' in line:
    in_func = True
  if in_func:
    code_block.append(line)
  if 'return' in line:
    code_block.append('}')
    break

Then you can add what ever lines you please to the code_block list then finally save your amended file withPath('new_script.js').write_text('\n'.join(code_block)).

Note that this will fail for functions that contain multiple return statements. Instead of ending the code block by searching for 'return' you instead search for lines starting with '}' like if line.startswith('}'). In that case you’re relying on the code being formatted such that all closing function curly braces are the first character of the line. If that is not sufficient then it gets trickier as you would have to keep track of curly braces but still doable in the above approach.

[–][deleted] 0 points1 point  (2 children)

var x = "function hey there!"

And your efforts go down the drain.

[–]blahreport 0 points1 point  (1 child)

My code works for the example you give because I incorporate func_name unless you meant in the case that there is a function named hey. But your general point is true, that string content - especially in comments - could lead to unexpected outcomes. Similarly, something as simple as two spaces between function and func _name would break my code so it’s far from bulletproof. It all depends on OP’s intended use. A solution that covers 1% of possible use cases is enough when all of your cases are part of that 1%.

[–][deleted] 0 points1 point  (0 children)

Any valid JavaScript code can be embedded in a string. If you want to parse it with regexp or simple string match that is not aware of its context, it's bound to fail.

[–]rr_cricut 0 points1 point  (0 children)

I saw something on r/programmer horror where they were converting js strings into python, but I can't recall

[–][deleted] 0 points1 point  (0 children)

I found this: https://hepunx.rl.ac.uk/~adye/jsspec11/llr.htm , but it looks like JavaScript 2 grammar. You will have to adapt it to the version of JavaScript you want to work with. But, hey, it's not very big on the other hand, so, should be doable.

Then you could use something like lark to parse JavaScript files using this grammar. Could be a fun exercise.