Also known as text.
They “string together” a series of individual characters.
So we can ask our usual questons
Basically any text (letters, numbers, etc.)
Two ways to write literal strings.
"foo"
'foo'
Note that the quotation marks are not part of the string.
Both "foo"
and 'foo'
are three characters long.
They also represent the same value despite being written differently.
+
operator works on stringsAlso known as “concatenation”
When asked to add different types of values, and one of them is a string, Javascript will convert the other one to a string and then concatenate them.
But the other arithmetic operators will convert strings to numbers in mixed expressions.
[]
operatorThe “index” operator.
Allows us to select a single character out of a string.
Unlike operators like +
and *
, it doesn’t go between its operands.
Also its operands are not the same type.
[
index]
The string operand is a string.
The index operand is a number.
Expression evaluates to a one-character string.
The index of the first character is 0
.
This is called a zero-based index.
An index tells you how many characters are ahead of the character at that index.
length
propertySome values in Javascript have “properties” that hold other values.
Strings have a length
property that says how long they are.
Properties are accessed with a .
after a value followed by the name of the property.
s
If the index of the first character is 0
what is the last valid index?
s.length - 1
Some values in Javascript have special properties called “methods”.
Methods are bits of functionality, similar to functions, but attached to the value.
value.methodName(arguments)
slice
methodSometimes we want to extract a bigger chunk of a string than a single character.
Strings have a slice
method for this.
From a starting index (inclusive) to an end index (exclusive)
s.slice(
start index,
end index)
or
s.slice(
start index)
Second argument is implicitly s.length
.
slice
A negative index to slice
is treated as if it was subtracted from the string’s length.
s.slice(-3)
is equivalent to
s.slice(s.length - 3)
s = 'foobar'
The indexOf
method can find where one string occurs in another.
s.indexOf("o")
⟹ 1
s.indexOf("oba")
⟹ 2
[]
and indexOf
Index operator []
takes an index (a number) and returns a one-character string.
s[3]
⟹ "b"
indexOf
takes a string argument and returns an index (a number)
s.indexOf("b")
⟹ 3
f = 'foo'
f[0].toUpperCase() + f.slice(1)
'Foo'