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

The Modern Web

Build modern and responsive webpages Try Front-end

The Modern Web will guide you through the most important tools of device-agnostic web development, including HTML5, CSS3, and JavaScript. The plain-english explanations and practical examples emphasize the techniques, principles, and practices that you'll need to easily transcend individual browser quirks and stay relevant as these technologies are updated.

$ Check price
34.9534.95Amazon 4.5 logo(30+ reviews)

More Front-end resources

Aching back from coding all day?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ reviews)

More Back Problems resources