Thursday, January 10, 2008

Imbedding Newlines in Interpreted Javascript

I've got a few new flash interfaces coming up. Unfortunately my hosting company has been down for the last week, so I can't upload anything yet... Grrr!
Meanwhile, in the course of my projects, I've discovered a simple but awesome javascript hack... OK, it's probably common knowledge in the Javascript community, but for this purpose I was stumping on the problem, and now I've figured out a workaround, so yay for me, it's my blog and I'll call it an awesome javascript hack if I want to, cause it sounds better and it makes me look smart... Is this thing on???

When writing jsx files for the flash panel interfaces (see my previous post for an example) one is required to imbed the entire script as a string, in the form:
"var a= 'Hello';\n"+
"var b= 'there';\n"+
"alert (a+' '+b+'!');\n"+
Note the \n (newline) characters at the end of each line. I've given a lot of thought to just #including external .js files to avoid this mess, but decided against it for the time being because it would create one more thing the end user would need to place in their scripts folder.
So, for now, I'm stuck with imbedding my scripts as strings. Unfortunately, I've used the " (double quote) and the \n (newline) characters liberally in all my scripts, and either of these characters will wreak havoc the continuity of the above formatting.
I easily search-and-replaced the double quotes with single quotes, but the newline character was giving me a bit of trouble. I used newlines in most of my prompt fields, and I didn't want to maintain two separate versions of my code.
After thinking about it for a while, I've found this workaround.
If the following Javascript were to be entered as a text string, the retChar variable won't terminate the line, but will display properly in the alert box.
var retChar = eval('String.fromCharCode(13)');
alert ( 'hello'+retChar+'there' );
The same could be done with the quote characters if you were backed into a corner, but it would be messy to use this solution for everything:
var quote = eval('String.fromCharCode(34)');
alert ( quote+'hello there' quote);
Anyway, If you're just reading this blog just to see what cool new scripts are out, and you couldn't give a crap about how it was coded, then don't worry, I think you'll find the next post a bit more rewarding. :)

1 comment:

Unknown said...

thanks man this helped ;-)