Understand Strings

What are strings?

Strings are a character or a string of characters.

String syntax

Strings are wrapped in matching single or double quotes.

'Just a plain old common string';

Escaped Characters

Imagine you are trying to print the following string:

console.log('Let's print this string!');

The ' in Let's ends the string instead of acting as an apostrophe. To show the second quote we can use a backslash before the quote. This tells the program you want the quotation mark to act as a quotation mark rather then the end of a string.

console.log('Let\'s print this string!');

The backslash works with a few other characters to create special meanings. For instance, if you want to show the backslash itself in the string then you need to use two backslashes.

console.log('Here is a backslash in code \\');

Or if you want a line break you can use \n.

console.log('This will be separated \n from this by a line break.');

String concatenation

String concatenation is a fancy way of saying combining strings. The plus sign will combine two different strings.

console.log('String one' + ' combined with string two');

Properties & Methods

Property

length

You can find the number of characters in a string by using the length property.

console.log('Jeremy'.length); // prints 6

Note the syntax; you have your string then a period followed by the word length.

Methods

charAt(x)

You can find the character at each index of a string by using charAt(x). Many things are zero indexed in computer science including the characters of a string. To find the first character you would use 0 not 1.

console.log('Jeremy'.charAt(0)); //Should print J

toUpperCase()

The toUpperCase() method returns a string with all upper case letters.

console.log('Jeremy'.toUpperCase()); // Should print JEREMY

toLowerCase()

The toLowerCase() method returns a string with all lowercase letters.

console.log('Jeremy'.toLowerCase()); // Should print jeremy

concat(x, y, ...)

The concat() method is another way of concatenating strings. The arguments are concatenated onto the original string.

console.log('Jeremy'.concat(' likes ', ' ice cream.'));