如何将 JavaScript 代码转换为一个大的 Java 字符串
所以我有 1000 行 javascript。 我需要将其转换为 Java 字符串,以便可以输出(通过 System.out.println 或其他方式)。
我正在寻找一个在线工具来转义所有引号...适合我的特定需求的东西会很好,因为我不希望更改其他特殊字符。 像这样的线条:
var rgx = /(\d+)(\d{3})/;
需要保持完整。
这种情况要求将 JavaScript 放入字符串中,因此请不要采取解决方法。
So I have 1000 lines of javascript. I need to turn it into a Java String so that I can output (via System.out.println
or whatever).
I'm looking for an online tool to escape all the quotes... something geared toward my specific need would be nice as I don't want other special characters changed. Lines like:
var rgx = /(\d+)(\d{3})/;
need to stay intact.
The situation mandates the JavaScript be put into a String so please no workarounds.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
以下链接介绍了 Crockford 的
quote()
函数实现 。 用它来构建您自己的 JavaScript 转换器。编辑:我也稍微修改函数,默认输出 ascii 安全字符串。
Edit2:只是一个建议:将 JavaScript 保存在外部文件中并在运行时读取它而不是对其进行硬编码可能会更明智...
Edit3:这是一个完整的-特色解决方案 - 只需复制到
.html
文件并替换虚拟脚本:Here's a link which features Crockford's implementation of the
quote()
function. Use it to build your own JavaScript converter.Edit: I also slightly modified the function to output an ascii-safe string by default.
Edit2: Just a suggestion: It might be smarter to keep the JavaScript in an external file and read it at runtime instead of hardcoding it...
Edit3: And here's a fully-featured solution - just copy to a
.html
file and replace the dummy script:您可以使用可用工具之一压缩文件来实现此效果:
YUI Compressor Online
迪恩·爱德华的 Packer
道格拉斯·克罗克福德的 JSMIN
You can compress the file using one of the available tools to achieve this effect:
YUI Compressor Online
Dean Edward's Packer
Douglas Crockford's JSMIN
您可以使用 jsmin 工具将 Javascript 压缩为一行(希望如此),但它并没有逃脱引号。 这可以通过编辑器中的搜索/替换或使用的服务器端脚本语言来完成。
You can use the jsmin tool to compress the Javascript to a single line (hopefully), but it doesn't escape the quotes. This can be done with search/replace in an editor or the server side scripting language used.
所以我尝试的一切最终都破坏了 javascript。 我终于通过执行以下操作使其正常工作:
使用 Notepad++:
按 Shift + Tab 多次以取消每行缩进
Do View -> 显示行尾
对 CR 字符重复该操作
突出显示“(引号字符)并执行“全部替换”与 \" (转义引号)...只需在替换提示中输入引号字符,由于某种原因,仅会抓取一些引号。
现在你有 1 个非常长的行...我最终不得不将 1 个字符串分成大约 2000 个字符长的行....疯狂的长行正在杀死 IE 和/或打破 Java 字符串限制。< /p>
So everything I tried ended up breaking the javascript. I finally got it to work by doing the following:
Using Notepad++:
Hit Shift + Tab a bunch of times to unindent every line
Do View -> Show End Of Line
Repeat for the CR char
Highlight a " (quote character) and do a Replace All with \" (escaped quote)... just typing the quote character into the Replace prompt only grabbed some of the quotes for some reason.
Now You have 1 enormously long line... I ended up having to break the 1 string apart into about 2000 character long lines.... The crazy long line was killing IE and/or breaking the Java String limit.