03. Strings

Declaring Strings

You can use either double or single quotes to declare a string.

"Hello world!"   // declaring with double quotes
'Hello world!'                 // with single quotes
'She said, "she said"'         // Using double quotes within single quotes
"She said, \"Hello darling\""  // Escaping quotes with a backslash

As you can see in the above example, you can use the backslash key \" to escape the quote.

Escape characters

JavaScript provides a list of other escape characters as well.

Form feed
Carriage Return
Vertical tab
//     Hello
// World!

String concatenation

To concatenate two strings together simply use the + operator.
var greeting = "Hello" + "world!";

Mixing numbers and strings

When adding numbers and strings together, you will get a string back, with the two values concatenated.

var cost = '8' + 9;   // cost = '89';

String properties and methods

The String object comes with a number of member attributes.

Number of characters in string.
Substring from m to the end.
Substring from m to but not including n.
Changes all casing to upper case.
Changes all casing to lower case.
Takes away whitespace away from both ends of a Stirng.
var sample = "Hello there."
sample.length;          // 12 characters
sample.substring(0,5);  // "Hello"
sample.toUpperCase();   // "HELLO THERE."

Capturing user input

To get input from your user, use the prompt() method. This will display a dialog box to the user, displaying the string passed in as an parameter to prompt().

var age = prompt("How old are you?");
// User is prompt for his age, which then gets placed in the age variable.
console.log(age); // outputs user's inputted age to the javascript console.

Build modern and responsive webpages


Build modern and responsive webpages Try Front-end

This book teaches HTML as if it's for anyone - hobbyists, students, and professionals - and it's full-color throughout. It utilizes information graphics and lifestyle photography to explain the topics in a simple way that is engaging. You can progress through the chapters from beginning to end or just dip into topics of particular interest at your leisure.

$ Check price
29.9929.99Amazon 4.5 logo(926+ reviews)

More Front-end resources

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources