string interpolation .... like perl

W

w i l l

I am beginning JavaScript, expect to see me in here a bit more over
the next few months :) I am currently writing some HTML with
JavaScript. As you know HTML has many double quotes ( " ) when
declaring attibute values, I know in some cases quotes are optional,
but I like them.


Here is something I've been playing with , it works, but in my
opinion, it's ulgy...

<script>
var myArray = new Array("blue","green","red");
for(var i = 0; i < myArray.length; i++) {
document.write("<input type=\"submit\" value=\"" + myArray +"\"
onClick=\"document.bgColor='" + myArray +"'\">");
}
</script>

Is there any way to mix javascript variables in with HTML without
having to excape all of the qoutes?

a perlish solution would be the qq operatior. but I know of nothing in
javascript. Is there anything?

perlish example...

document.write(qq` an example of " any text" ... `);


TIA

w i l l
 
L

Laurent Bugnion, GalaSoft

Hi,
I am beginning JavaScript, expect to see me in here a bit more over
the next few months :) I am currently writing some HTML with
JavaScript. As you know HTML has many double quotes ( " ) when
declaring attibute values, I know in some cases quotes are optional,
but I like them.


Here is something I've been playing with , it works, but in my
opinion, it's ulgy...

<script>
var myArray = new Array("blue","green","red");
for(var i = 0; i < myArray.length; i++) {
document.write("<input type=\"submit\" value=\"" + myArray +"\"
onClick=\"document.bgColor='" + myArray +"'\">");
}
</script>

Is there any way to mix javascript variables in with HTML without
having to excape all of the qoutes?


JavaScript considers " (double-quotes) and ' (single-quotes) as
equivalent (unlike other languages!) and allows you this kind of
construction:

var myString = 'This string says "Hello world"...';

However, there are situations where escaping is not avoidable. You will,
in your programmer's life, have to escape other characters too, like \\,
\t, \n, \r etc... After a while, you will stop noticing it and be able
to read escaped code as easily as unescaped ones. It's just a matter of
experience. It's the same in most advances languages anyway.

HTH,

Laurent
 
D

Douglas Crockford

Make that

document.write('<input type="submit" value=' + myArray.quote() + '
onclick=' + ('document.bgColor=' + myArray.quote() + ';').quote() + '>');
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top