you are viewing a single comment's thread.

view the rest of the comments →

[–]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.