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.

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

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