How to Use Text in JavaScript Strings - dummies

How to Use Text in JavaScript Strings

By Chris Minnick, Eva Holland

In JavaScript programming, a piece of text inside of quotes is called a string. You can remember this name by thinking of text inside quotes like a piece of string with letters, numbers, and symbols tied to it. These letters stay in the same order, and each one takes up a certain amount of space on the string.

For example, try typing this code into your JavaScript console again, but change Coding is fun! to another message, such as what you want for lunch or dinner:

for (var i = 0; i < 300; i++) { document.write ("Coding is fun!"); }

The figure shows the output of the program when the message is changed to “I want pizza for lunch!”

Changing a string only changes the string.
Changing a string only changes the string.

Any character you can type can be put into a string. However, there’s one important exception that you need to remember: If you want to use quotation marks inside a string, you have to tell JavaScript that the quotation marks are part of the string, rather than the end of the string.

The way to put quotation marks inside a string is by using a backslash () before the quotation marks. Using the backslash in a string tells JavaScript that the next character is something special and doesn’t mean what it normally would mean. When you add a backslash before a quotation mark in a string, it’s called escaping the quotation mark.

For example, if you want to change the string to:

Joe said, "Hi!"

You would need to write the string as:

"Joe said, "Hi!""