How to create a string
The strings are created with matching single quotes, double quotes, or backticks:
1"Hello, World!";
1// prettier-ignore
2'Hello, World!'
1`Hello, World!`;
The string created with backticks is a special type of string in JavaScript, as they allow you to interpolate variables and expressions inside:
1`half of 100 is ${100 / 2}`;
In this example, the division operation inside ${}
will be calculated first, and the result will be converted into a string and embedded into that position. So this example will give us:
You can interpolate almost anything inside ${}
, such as variables, functions, and so on. This feature is also referred to as template literals.
String encoding
Just like numbers, strings will also be compiled into binary code. JavaScript uses 16-bit binary code to represent each string character, which means it is able to encode 2^16
different characters.
That seemed like a good idea when JavaScript was first created, but nowadays, the Unicode standard defines a lot more characters than that. To address this issue, UTF-16 (16-bit Unicode Transformation Format) was created. It represents the most common characters using 16-bit code, but the less common characters, such as emojis, would take up two of those 16-bit codes.
To prove that:
.length
is how you can retrieve the length of a string. As you can see, the emoji "😀"
is twice as long as the string character "a"
.
String concatenation
The +
operator can be used on strings as well. But obviously, you can not perform arithmetic operations on strings, the +
sign here means concatenate (joining two strings together).
1"Hello" + " " + "World" + "!";
Note that space (" "
) is also a character and should not be left out. It is not the same as an empty string (""
).
You can also use the concatenate operator to join the string with a variable.
1let err = 1234;
2
3console.log("Error Code: " + err);
1Error Code: 1234
JavaScript will automatically convert the number 1234 into a string.
A different way to do this would be using the template literal.
1let err = 1234;
2
3console.log(`Error Code: ${err}`);
1Error Code: 1234
Special characters
JavaScript gives the backslash (\
) a special purpose when it is inside a string. It defines a few special characters, as shown in the list below:
\n
: the newline character
\n
defines a newline character in a string.
1console.log("Hello,\nWorld!");
1Hello,
2World!
\t
: the tab character
\t
defines a tab character in a string.
1console.log("Hello,\tWorld!");
1Hello, World!
\'
,\"
: quotes
If you want a quotation mark inside the string, our previous solution was to mismatch the quotes, using a different pair of quotes to define the string. But this solution is not optimal, especially if the project you are working on has a specific style guide and you are required to use either single or double quotes to define the strings.
In this case, you could use the \'
and \"
characters instead.
1// prettier-ignore
2console.log("First Name: \"John\"");
1First Name: "John Doe"
\\
: backslash
Lastly, if you want a backslash inside the string, use \\
.
1console.log("Hello\\World!");
1Hello\World!
String comparison
You can also perform comparison operations on strings using the same operators we've discussed before.
1console.log("1" < "2");
2console.log("a" > "b");
3console.log("a" >= "a");
4console.log("a" <= "A");
1true
2false
3true
4false
The string characters are ordered alphabetically, which means "a"
is less than "b"
, "b"
is less than "c"
, and so on. The uppercase letters are all less than lowercase letters, which means "Z"
is less than "a"
.
This is where things get interesting. Consider this scenario: what happens when we compare two values of different types? For example:
1console.log(1 == "1");
Surprisingly, this comparison returns true
. If you are familiar with other programming languages, you'll know that this is very unusual. Most programming languages are very strict about data types, and they would not recognize two values of different data types to be equal.
JavaScript, however, is very flexible in that regard. It will automatically convert the values to be the same data type if possible, even though sometimes it doesn't make sense. We'll discuss more about this behavior later.
If you want JavaScript to take data types into account, use ===
instead, which means equal value and equal type, sometimes referred to as strict equal.
1console.log(1 === "1");
2
3console.log(1 === 1);
1false
2true
String methods
Compared to numbers, there are a lot more methods associated with the string type. We will only introduce the most commonly used ones in this lesson. If you are interested, here is a list of all string methods available in JavaScript.
charAt()
The charAt()
method returns the character at the specified index.
1let str = "qwerty";
2
3console.log(str.charAt(0));
4console.log(str.charAt(2));
5console.log(str.charAt(4));
1q
2e
3t
Remember that the index starts from 0 in JavaScript, not 1, so index 0 corresponds to the character q
in this example.
indexOf()
This method returns the index of the specified character when it first occurred in the string.
1let str = "abcba";
2
3console.log(str.indexOf("b"));
11
Notice that even though b
occurred twice in the string, only one value is returned.
length
length
is technically not a method, it is called a property. We will talk about their differences later in the objects lesson.
For now, you only need to know that this property returns the number of characters in the string.
1let str = "abcba";
2
3console.log(str.length);
15
slice()
The slice()
method extracts a part of the string based on the given indexes.
1let str = "qwerty";
2
3console.log(str.slice(1, 3)); // Extract characters between index 1 (inclusive) and index 3 (exclusive).
4console.log(str.slice(2)); // Extract characters from index 2 to the end
1we
2erty
split()
The split()
method splits the string based on the given character and returns an array of substrings. This is one of the most useful methods for strings. For example, if given a URL, you can use the split()
method to extract the slug.
1let url = "https://thedevspace.io/course/javascript-strings";
2
3let arr = url.split("/");
4
5console.log(arr);
6
7let slug = arr[4];
8
9console.log(slug);
1[ 'https:', '', 'thedevspace.io', 'course', 'javascript-strings' ]
2javascript-strings
toLowerCase()
andtoUpperCase()
These are two similar methods that convert the string into lower or upper letters.
1let str = "Qwerty";
2
3console.log(str.toLowerCase());
4console.log(str.toUpperCase());
1qwerty
2QWERTY
trim()
Returns a string with the leading and tailing white spaces removed.
1let str =
2 "\tLorem ipsum dolor sit amet consectetur adipisicing elit.\n Assumenda, quaerat perferendis nam vitae harum iusto repellendus suscipit, ipsa fugit aliquid sapiente modi non qui doloremque inventore.\n Mollitia, tempora?\t Soluta, voluptatibus.\t";
3
4console.log(str.trim());
1Lorem ipsum dolor sit amet consectetur adipisicing elit.
2 Assumenda, quaerat perferendis nam vitae harum iusto repellendus suscipit, ipsa fugit aliquid sapiente modi non qui doloremque inventore.
3 Mollitia, tempora? Soluta, voluptatibus.
Notice that the \t
characters at the beginning and end of the string are removed, but the white spaces in the middle are preserved.