Home

How to Use Text in JavaScript Strings

|
Updated:  
2016-03-26 07:26:32
|
JavaScript Essentials For Dummies
Explore Book
Buy On Amazon

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!""

About This Article

This article is from the book: 

About the book author:

Chris Minnick is an accomplished author, teacher, and programmer. Minnick authored or co-authored over 20 books, including titles in the For Dummies series. He has developed video courses for top online training platforms and he teaches programming and machine learning to professional developers at some of the largest global companies.

Eva Holland is an experienced web developer, tech trainer, and coauthor of Coding with JavaScript For Dummies. She is a co-founder of WatzThis?, a company focused on training and course development.