A string is a series of zero or more characters grouped together inside single or double quotes.
In order to define a
string, we must do it by starting and ending with either single or double quotes.
Problems, however, might arise, if we have to include a literal quote
' inside the
The code above will generate an error on the console:
To fix this problem, we can escape the quote from being considered as the end of the string quote by using the backslash
\ in front of the quote:
It's important to not abuse backslash
\ character; since it can make our code more difficult to read.
For this reason, we can always use single quotes for our string variables and use double quote only when needed inside the variable, like in the code below:
Escape Sequences in Strings
Concatenating Strings with Plus Operator
+ operator also inside a
String value, and in that case it's called
This operator is very helpful to concatenate together multiple strings in order to build a new one.
Concatenating Strings with the Plus Equals Operator
We can concatenate strings together also by using the
Constructing Strings with Variables
+ operator can be used not only to concatenate
Strings, but also to build a new string by inserting one or more variables into it.
Appending Variables to Strings
We can append variables to a string using the plus equals
Find the Length of a String
If we want to calculate the length of a
String, we can write
.length at the end of the string variable or string literal.
Use Bracket Notation to Find the First Character in a String
bracket notation to get a character at a specific index within a string. Moreover, instead of starting to count at 1, we start at 0. This is referred to as
For example, the character at index 0 in the word "Charles" is "C". So if
var firstName = "Charles", you can get the value of the first letter of the string by using
Understand String Immutability
immutable. This means that they cannot be modified once created.
As we can see from the code above,
String immutability doesn't mean that the string variable cannot be changed, just that the single individual character of a
string literal cannot be changed.
That's why the only way we can change
myStringVariable is to assign it with a completely new string:
Use Bracket Notation to Find the Nth Character in a String
We can use
bracket notation also to get a particular character's position within a string.
Use Bracket Notation to Find the Last Character in a String
Bracket Notation allows us to make also some basic logic and find the last letter of a string. We can do it by subtracting one from the string's length.
Use Bracket Notation to Find the Nth-to-Last Character in a String
In the same way we calculated the last character in a string, we can retrieve also the Nth-to-last character.