【问题标题】:How to replace all symbol names in a javascript project如何替换javascript项目中的所有符号名称
【发布时间】:2013-01-05 02:13:10
【问题描述】:

我想编写一些自动(使用规则系统和用作替换的单词列表)应该用其他东西替换所有变量和函数名称的东西:

例如:

var foot = 0;
function cat(state) {
    return state ? "running" : "sleep";
}
cat(foot);

收件人:

var house = 0;
function bear(country) {
    return country ? "running" : "sleep";
}
bear(house);

我已经在网上搜索过,但没有找到任何可以轻松修改的项目。

你们中是否有人知道如何执行此操作或知道我可以将其用作起点的项目?

【问题讨论】:

  • 您希望这是运行时还是构建时?
  • 这是一个ide吗?有点像智能查找/替换
  • 可能是使用sedgrep 的shell 脚本?
  • Notepad++ 中的“查找和替换”命令会产生奇迹:)
  • 不是换词那么简单。您将需要编写一个复杂的过程来读取 Javascript 并区分用户定义的函数名称和变量名称。

标签: javascript parsing


【解决方案1】:

您是在寻找Obfuscator 还是您喜欢做什么?

How can I obfuscate (protect) JavaScript?

【讨论】:

  • 我正在考虑为此目的使用混淆器,但我发现没有一个可以让我控制名称将被替换为什么。
  • 在这种情况下,我更愿意在netbeans.org 中打开代码然后右键单击函数/变量定义重构-> 重命名
【解决方案2】:

您可以编写一个简短的 Shell 脚本(例如 bash)。您需要sedfor 循环以及三个包含单词列表的变量。如果您的第一个代码包含脚和猫以及名为 my_first_code.txt 的文件中的状态,那么它将如下所示:

foot_words="house ba be bi bo bu"
cat_words="bear da de di do du"
state_words="country ka ke ki ko ku"

count=1
for word in $foot_words; do
    sed 's%foot%'$word'%g' my_first_code.txt > new_code_$count.txt
    ((count++))
done
count=1
for word in $cat_words; do
    sed -i 's%cat%'$word'%g' new_code_$count.txt
    ((count++))
done
count=1
for word in $state_words; do
    sed -i 's%state%'$word'%g' new_code_$count.txt
    ((count++))
done

在本例中,您将获得 6 个新文件 new_code_1.txtnew_code_2.txtnew_code_3.txt 等等。

解释:第一个for 循环复制my_first_code.txt 中的代码,并用新词 替换词foot。另外两个for 循环只是替换新文件中的单词。

【讨论】:

    【解决方案3】:

    Google Closure Compiler (https://developers.google.com/closure/compiler/) 能够识别函数和变量名称,但没有内置选项可以用您选择的名称替换它们。

    因为直接查找和替换没有上下文,如果你想滚动你自己,你需要使用正则表达式来“解析”JavaScript,如果你使用递归正则表达式,这很困难但易于管理,例如在带有平衡组的 .NET 中

    http://msdn.microsoft.com/en-us/library/bs2twtah.aspx

    get inner patterns recursively using regex c#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 2012-03-02
      相关资源
      最近更新 更多