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

JavaScript & JQuery

Build modern and responsive webpages Try Front-end

This book was written for anyone who wants to use JavaScript to make their websites a little more interesting, engaging, interactive, or usable. In particular, it is aimed at people who do not have a degree in computer science (well, not yet anyway).

$ Check price
39.9939.99Amazon 4.5 logo(385+ reviews)

More Front-end resources

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources