Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert JavaScript code into one big Java string

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.


1 Answers

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:

<script src="quote.js"></script>
<script>
// this is the JavaScript to be converted:
var foo = 'bar';
var spam = 'eggs';

function fancyFunction() {
    return 'cool';
}
</script>
<pre><script>
document.writeln(quote(
    document.getElementsByTagName('script')[1].firstChild.nodeValue, true));
</script></pre>
like image 96
Christoph Avatar answered May 23 '26 00:05

Christoph