× Introduction Setup Environment Building blocks Built-in functions Data Types Strings Operators Conditional statements Loop statements Functions Arrays Understaing Objects Date Object Number Object Math Object String Object Window Location Navigator History DOM Basics Forms
   Programs
Basic Control Loops Functions Arrays Examples Projects Quick Ref.
   Exercises
Variables Data Types Operators Decision Loops Reeborg's World



Working with Strings

In this tutorial you will learn about strings and string operations

A text string contains zero or more characters surrounded by doubleor single quotation marks. Examples of strings you may use in a script are student names,usernames, and message. A literal string can also be assigned a zero-length string value called an empty string.

A string must begin and end with the same type of quotation marks.

For example, you can use either: Try It

document.write("Hello, 'Java Script' programming");
or
document.write('Hello, "Java Script" programming');

document.write("Hello, World')  // invalid

String Operators:

JavaScript has two operators that can be used with strings: + and +=. When used with strings, the plus sign is known as the concatenation operator. The concatenation operator (+) is used to combine two strings.

For example, the following code combines a literal string and a string variable: Try It

var name = "Ram";
alert("Hello! " + name);

For example, the following code combines a string variables and a literal strings: Try It

var name = "Ram";
var age = 15;
alert(name + " of Age:  " + age +" years" );

We can also use the compound assignment operator (+=) to combine two strings. Try It

var name = "Ram";
name += " of age " + 25;
alert(name);

Escape Characters and Sequences:

We need to use extra care when using single quotation marks in strings, because JavaScript interpreters always look for the first closing single ordouble quotation mark to match an opening single or double quotation mark. For example, consider the following statement: Try It

alert('Let's learn JavaScript');

This statement causes an error.

To get around this problem, we include an escape character before the apostrophe in “Let’s”. An escape character tells compilers and interpreters that the character that follows it has a special purpose. In JavaScript, the escape character is the backslash ( \). Placing a backslash before an apostrophe tells JavaScript interpreters that the apostrophe is to be treated as a regular keyboard character, such as a, b, 1, or 2, and not as part of a single quotation mark pair that encloses a text string.

The escape character has even more purposes. You can use it to create a line break with \n, or to include a backslash character in the text with \\:

Example:

console.log("New \nline.");
console.log("I'm containing a backslash: \\!");
console.log("I'm containing a \ttab!");