Jared
Jared

Reputation: 39893

Multi line string containing special characters in javascript?

I'm trying to use the javascript port of processing found at http://ejohn.org/blog/processingjs/ I want to use the following constructor. Processing(CanvasElement, "some massive block of code"); I know javascript doesn't natively support multiline strings but is there a way to pass something like the following with out having to concatenate every line and escape every special character?

/**
 * Array. 
 * 
 * An array is a list of data. Each piece of data in an array 
 * is identified by an index number representing its position in 
 * the array. Arrays are zero based, which means that the first 
 * element in the array is [0], the second element is [1], and so on. 
 * In this example, an array named "coswav" is created and
 * filled with the cosine values. This data is displayed three 
 * separate ways on the screen.  
 */

size(200, 200);

float[] coswave = new float[width];

for (int i = 0; i < width; i++) {
  float amount = map(i, 0, width, 0, PI);
  coswave[i] = abs(cos(amount));
}

for (int i = 0; i < width; i++) {
  stroke(coswave[i]*255);
  line(i, 0, i, height/3);
}

for (int i = 0; i < width; i++) {
  stroke(coswave[i]*255 / 4);
  line(i, height/3, i, height/3*2);
}

for (int i = 0; i < width; i++) {
  stroke(255 - coswave[i]*255);
  line(i, height/3*2, i, height);
}

Upvotes: 0

Views: 4144

Answers (5)

Crescent Fresh
Crescent Fresh

Reputation: 116998

For a more maintainable solution, I would place it in script tags tags in the body of the page, eg:

<script type="text/processing" id="code">
/**
 * Array. 
 * ...
 */

size(200, 200);
...
</script>

And construct your Processing object like:

var canvas = document.getElementById('canvas');
var code = document.getElementById('code');
Processing(canvas , code.textContent);

For a quick and dirty solution run your processing code through a JSON encoder as RoBorg suggested and you'll get a string that you can just copy and paste into the second parameter.

Upvotes: 1

vava
vava

Reputation: 25381

Another option would be to use E4X literals

var s = "" + <r><![CDATA[
line 1
line 2
]]></r>;

Although I doubt it is supported by IE6.

Upvotes: 0

PhiLho
PhiLho

Reputation: 41152

Alternatively, you can just put the text in the HTML page (hidden, for example) and get it from there...

Upvotes: 0

Greg
Greg

Reputation: 321766

Javascript actually does support multi-line strings: append a backslash to the end of each line:

alert('1\
    2\
    3');

Not very pretty, but it works.

An alternative would be to use a script to encode your text... I'd suggest PHP as it's a 1-liner:

<?=json_encode('your text');?>

Upvotes: 3

AnthonyWJones
AnthonyWJones

Reputation: 189495

Place the "massive block of code" in its own file on the server, fetch with AJAX and ensure it has reasonable cache headers.

Upvotes: 0

Related Questions