Java Reference
In-Depth Information
Concatenating Strings
trY it out
Let's look at an example using the + operator for string concatenation.
1.
Type the following code and save it as ch2_example5.html :
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Chapter 2, Example 5</title>
</head>
<body>
<script>
var greetingString = "Hello";
var myName = prompt("Please enter your name", "");
var concatString;
document.write(greetingString + " " + myName + "<br/>");
concatString = greetingString + " " + myName;
document.write(concatString);
</script>
</body>
</html>
2.
If you load it into your web browser, you should see a prompt box asking for your name.
3.
Enter your name and click OK. You should see a greeting and your name displayed twice on the
web page.
You start the script block by declaring three variables. You set the first variable, greetingString , to a
string value. The second variable, myName , is assigned to whatever is entered by the user in the prompt
box. You do not initialize the third variable, concatString , here. It will be used to store the result of
the concatenation that you'll do later in the code.
var greetingString = "Hello";
var myName = prompt("Please enter your name", "");
var concatString;
In the previous chapter, you saw how the web page was represented by the concept of a document and
that it had a number of different properties, such as bgColor . You can also use document to write text
and HTML directly into the page itself. You do this by using the word document , followed by a dot,
and then write() . You then use document.write() much as you do the alert() function, in that you
put the text that you want displayed in the web page inside the parentheses following the word write .
Don't worry too much about this here, though, because it is all explained in detail in later chapters.
However, you now make use of document.write() in your code to write the result of an expression to
the page:
document.write(greetingString + " " + myName + "<br/>");
Search WWH ::




Custom Search