Web Development Tutorials


String Operations

A text string is a sequence of alphabetic, numeric, and other characters, enclosed in quotes, and treated as a block of text. Of course, you cannot perform arithmetic operations on strings but you can concatenate strings, which means to link together two or more separate strings into a single string of text. Concatenation is accomplished with the concatenation operator (+), which uses the same symbol as the addition operator, but, when applied to string data, links two or more strings together into a single line of text.

Assume, for example, you have declared the following variables.

var FirstString = "To be or not to be,";
var SecondString = "that is the question.";

You can put these two separate strings together as a single sentence by concatenating them and assigning the resulting string to a variable.

var FullString = FirstString + " " + SecondString;

Now variable FullString contains the text "To be or not to be, that is the question." Note that a literal blank space (" ") is concatenated between the two individual strings to insert a space between the two clauses in the final sentence.

Computer Memory:


Figure 2-19. Concatenating strings.

You should be aware that numerals can appear within strings if they are not intended for arithmetic operations. For example, you can define

var Numeral1 = "20";
var Numeral2 = "06";
var Result = Numeral1 + Numeral2;

The Result produced is the value "2006", not 26. The variables are concatenated rather than added because the numerals are defined as character strings by enclosing them in quotes.

By the same token, JavaScript concatenates rather than adds if any one of the variables or literals in the expression is a text string. For instance, assume the following assignments.

var Number = 20;
var String = "06";
var Result = Number + String;

In this case, the Result value is also "2006". Since JavaScript cannot perform arithmetic using the string data in variable String, it converts the value of variable Number to string characters and treats the "+" sign as a concatenation operator.

Whether concatenation or addition takes place depends on the data types involved. JavaScript evaluates the values and, if any one of them is a string, applies concatenation. Otherwise, it performs addition.

You can include the concatenation operator along with text strings and variables in the alert() method to dress up your script output displays. In the following example, a function is called to make a calculation. The result is displayed along with a string to label the output.

function Calculate() {
  var X = 10;
  var Y = 20;
  var Z = 2;
  var Answer = X + (Y / Z);
  alert("The answer is " + Answer);

Listing 2-11. Code to concatenate strings for display with the alert() method.

In this case, the "+" operator in the alert() expression is interpreted as a concatenation operator because at least one of the values in the expression ("The answer is ") is a text string. Arithmetic cannot be performed with a string value, therefore, the "+" operator is taken to mean concatenation.

Several concatenations can appear together to compose lengthier strings. In the following example, prompt() boxes are displayed for the user to enter a first and last name. These entered values are then concatenated with other literal strings to compose a complete sentence displayed in an alert() box.

function Get_Name() {
  var FirstName = prompt("Enter your first name:", "");
  var LastName = prompt("Enter your last name:", "");
  alert("Your name is " + FirstName + " " + LastName + ".");

Listing 2-12. Code to concatenate strings and input variables for display.

There are many other operations besides concatenation that can be performed on strings. These operations are included in a set of built-in string methods supplied by JavaScript that are discussed later.

The parseInt() and parseFloat() Methods

In a previous example of using the prompt() method (Listing 2-10), numbers are entered into prompt boxes and are multiplied. The relevant statements taken from this example are

var No1 = prompt("Enter the first number:", "");
var No2 = prompt("Enter the second number:", "");
var Product = No1 * No2;

As long as numeric characters are entered, the correct answer is produced. However, this example would not work correctly if the two numbers are added: No1 + No2. The reason is that data entered into prompt boxes are treated as strings. As long as multiplication (or division or subtraction) is applied to the values, JavaScript converts the strings to numbers and applies the arithmetic operator. For addition, though, the "+" operator is interpreted as concatenation because both entered values are strings. This interpretation is not peculiar to prompt boxes. All methods of user input treat the entered data as strings. Therefore, it is usually necessary to explicitly convert entered data to numeric values when addition is to be performed.

JavaScript provides two methods to convert character strings to numbers. First, the parseInt() method converts a string containing numeric characters to an integer value.


Figure 2-20. General format for parstInt() method.

As long as the first character in the string is numeric, any contiguous set of numerals are extracted from the string and treated as an integer value. Any remaining characters in the string are ignored. The companion parseFloat() method works the same.


Figure 2-21. General format for parseFloat() method.

The first character in the string is tested. If it is a numeral, any contiguous set of numerals, plus a decimal point, are extracted from the string and treated as a floating-point number. Any remaining characters in the string are ignored.

Use of the parseFloat() method - and by implication the parseInt() method - can be illustrated by a rewrite of the previous multiply script, this time adding together two numbers entered into prompt boxes.

function Add() {
  var No1 = prompt("Enter first number:", "");
  var No2 = prompt("Enter second number:", "");
  var Sum = parseFloat(No1) + parseFloat(No2);
  alert("The sum is " + Sum);

Listing 2-13. Code to add two values entered into prompt boxes.

The parseFloat() method converts both of the entered values to floating-point numbers. Therefore, the "+" operator can function as intended, as the addition operator.

Note that the converted values are added together and assigned to variable Sum, which is then displayed with the alert() method. Although it might be tempting to skip this step and to apply the parseFloat() method as part of the alert() method,

alert("The sum is " + parseFloat(No1) + parseFloat(No2))

this syntax does not work. It concatenates rather than adds the two numbers. The reason is that the first portion of the output string ("The sum is ") is itself a string. Therefore, even though the two numeric values are converted to numbers, they are concatenated since at least one of the values connected with "+" operators is a string.

The eval() Method

A third way of converting input strings to numbers is by applying the JavaScript eval() method. The general format for this method is shown below.


Figure 2-22. General format for eval() method.

Here, expression is any combination of strings, numbers, variables, and/or arithmetic operators that, taken together, are in the format of a valid JavaScript statement. The eval() method then executes the expression as a JavaScript command.

For instance, a script can compose a JavaScript alert() statement by concatenating the following elements:

var Message = "The answer is ";
var Answer = 10;
var Statement = "alert('" + Message + Answer + "')";

The completed concatenations assigned to variable Statement is a string value representing a valid JavaScript alert() statement: "alert('The answer is 10')". Now, by issuing the eval() method for this expression,


variable Statement is "run" and an alert box is displayed with the message.

This is quite a powerful method since it means you can use scripts to write scripts, a technique investigated more fully later. A more modest use is to return the numeric equivalent of a string of characters, much like the parseInt() and parseFloat() methods, but with added capabilities.

Recall that the alert() method can display the result of an arithmetic expression. An example used before is

alert( (10 + (20 / 30)) / 3.5 );

where the displayed value 3.0476190476190474 is produced. However, the alert() method cannot accurately display the result of this expression when it is input through a prompt box. The prompt() method always returns a string, so the expression itself, rather than its calculation, is displayed. The following script demonstrates, with the previous expression precoded as the default value of the prompt box.

function Calculate()
  var Expression = prompt("Enter your calculation:", "(10 + (20 / 30)) / 3.5");

Listing 2-14. Entering and displaying an arithmetic expression through a prompt box.

Here's where the eval() method comes into play. By "evaluating" the expression entered into the prompt box it is interpreted, not as a text string, but as a JavaScript statement - as an arithmetic expression. By recoding the alert() method as


the entered Expression is evaluated properly - as an arithmetic expression - and the result of the computation is displayed.

You can, therefore, create a script that permits you to enter any valid arithmetic expression and have JavaScript return the correct answer.

function Calculator() {
  var Expression = prompt("Enter your calculation:", "");
  alert("The answer is " + eval(Expression));

Listing 2-15. A JavaScript calculator.

There is no confusion over "+" operators appearing in the entered expression string. They all are treated as addition operators since all other parts of the string are numbers, decimal points, or parentheses, all valid, non-string characters in an arithmetic expression. The result of the expression, however, is converted to a string for display along with the string "The answer is ".

TOP | NEXT: The Math Object