简体   繁体   中英

Regex operations on Javascript functions

I'm trying to find function names in Javascript and insert the following code

var functionName = arguments.callee.toString().substr('function '.length);
functionName = functionName .substr(0,functionName .indexOf('('));
console.log(functionName);

This will write the name of the function to the console as it's called. I am not having much luck with this. I've been trying variants of this with sed.exe:

sed "{/function/ s/$/\var ownName = arguments.callee.toString().substr('function '.length);ownName = ownName.substr(0,ownName.indexOf('('));console.log(ownName);/}" *.js

This is just in the format sed "/elephant/ s/$/\\&castle" *.js

Anyone have any idea how I can send what I'm appending to the next line, rather than on the same line as function? Also, how can I imlement the following (but in sed.exe) to avoid anonymous function and eval functions??

grep -Eho "^s*function w+" *.js | sort

Thanks for the help.

Adding \\n into the replacement string works for GNU sed. I changed the regex you have for grep into ^[[:blank:]]*function \\w\\+ for sed and changed the condition of your s statement to that, and it worked properly. Here's the whole command in bash syntax:

sed "/^[[:blank:]]*function \\w\\+/ s/\$/\\nvar ownName = arguments.callee.toString().substr('function '.length);\\nownName = ownName.substr(0,ownName.indexOf('('));\\nconsole.log(ownName);\\n/" *.js

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