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.

\b
Backspace
\f
Form feed
\n
Newline
\r
Carriage Return
\t
Tab
\v
Vertical tab
\\
Backslash
document.write("\tHello\nWorld!");
//     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.

length
Number of characters in string.
substring(m)
Substring from m to the end.
substring(m,n)
Substring from m to but not including n.
toUpperCase()
Changes all casing to upper case.
toLowerCase()
Changes all casing to lower case.
trim()
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

High Performance Web Sites

Build modern and responsive webpages Try Front-end

Want your web site to display more quickly? This book presents 14 specific rules that will cut 25% to 50% off response time when users request a page. Author Steve Souders, in his job as Chief Performance Yahoo!, collected these best practices while optimizing some of the most-visited pages on the Web.

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

More Front-end resources

Ad