December 21, 2024
Answer to JavaScript Exercise
i)
a)
window.alert('Here\'s some stuff about JavaScript')
//also you can use "" delimiters
window.alert("Here's some stuff about JavaScript")
Notes:
- In my first solution to i)a), to output an apostrophe and to escape the JavaScript interpreter "reading" it as a delimiter of a string, I have written \'
- In my second version I have nested the apostrophe between "" delimiters. JavaScript permits use of either, but aim to be consistent
b)
document.write('Please note:' + '<br>' +
' You do not require a dialogue box.')
Notes:
- The JavaScript + operator is "overloaded", which means it has more than one meaning depending on context. If either operand to the + operator is a string, the interpreter will convert the other operand to a string (no matter what it is) and concatentate, or join, the two strings. Of course the other meaning of + is to add two numbers - more on this later.
- To make a line break in a browser you must code an HTML break tag <BR> into the output string.
- You are not tested on this here, but to build a carriage return or line break into a string that is to be output to an alert box you will need to use '\n'. This works in Netscape, but '\r', which does the same, only works in MSIE.
ii)
var aString; //declare a variable
aString = '"Help!"'; //store a string in the variable
document.write('<EM>' + aString + '</EM>, she cried.');
Notes:
- There was a missing string delimiter after the final "
- The JavaScript comment began with a single / instead of //
- The final line was missing a delimiter after the first string that constructed the <EM> tag
- To display a quote one needs to use nest "" inside the '' delimiters of the string
- I have used <EM></EM> tags for emphasised text, although one could use <I></I> tags. Once again you will need to build the HTML tags into your code.
- I could have written part ii) in a far simpler form
document.write('<EM>"Help!"</EM>, she cried.'); - I wanted to demonstrate the use of passing a variable as an argument
to the write method and concatenating this with a string representing
an HTML tag. (The use of a variable will be put to better use in later questions)
'<EM>' + aString - Remember that to output a string to an alert box use window.alert(someString)
- To output to a brower use document.write(someString)
Back « JavaScript strings
⇑ Up to top of page