Loading course content...
Loading course content...
Code Playground is only enabled on larger screen sizes.
A string is a series of characters enclosed inside matching quotes. JavaScript allows single quotes, double quotes, or backticks:
"Hello, World!";// prettier-ignore
'Hello, World!'`Hello, World!`;The string created with backticks is special in JavaScript, as they allow you to interpolate expressions like this:
`half of 100 is ${100 / 2}`;In this example, the expression inside ${} will be evaluated, and the result will be converted into a string and embedded into that position.
So the above example will give:
The backtick strings are also referred to as template literals.
Just like numbers, strings will also be compiled into binary code.
JavaScript uses a 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.
Test this in the console:
console.log("😀".length); // -> 2.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".
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).
"Hello" + " " + "World" + "!";Note that space (" ") is also a character and should not be overlooked. It is not the same as an empty string ("").
You can also use the concatenate operator to join the string with a variable.
let err = 1234;
console.log("Error Code: " + err);Error Code: 1234JavaScript will automatically convert the number 1234 into a string.
A different way to do this would be using the template literal, which is much more readable in this case:
let err = 1234;
console.log(`Error Code: ${err}`);Error Code: 1234JavaScript 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.
console.log("Hello,\nWorld!");
// ->
// Hello,
// World!\t: the tab character\t defines a tab character in a string.
console.log("Hello,\tWorld!"); // -> Hello, World!\', \": quotesIf 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, what if you need to use both single and double quotes in the string?
In this case, you could use the \' and \" characters instead.
// prettier-ignore
console.log("User\'s First Name: \"John\""); // -> User's First Name: "John Doe"\\: backslashLastly, if you want a backslash inside the string, use \\.
console.log("Hello\\World!"); // -> Hello\World!You can also perform comparison operations on strings, using the same operators we've discussed before.
console.log("1" < "2"); // -> true
console.log("a" > "b"); // -> false
console.log("a" >= "a"); // -> true
console.log("a" <= "A"); // -> falseThe string characters are ordered alphabetically, which means "a" is less than "b", "b" is less than "c", and so on.
All uppercase letters are 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:
console.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 when doing comparison, use === instead, which means equal value and equal type, sometimes referred to as strict equal.
console.log(1 === "1"); // -> false
console.log(1 === 1); // -> trueCompared to numbers, there are a lot more utility 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.
let str = "qwerty";
console.log(str.charAt(0)); // -> q
console.log(str.charAt(2)); // -> e
console.log(str.charAt(4)); // -> tRemember that the index starts from 0, not 1, so index 0 corresponds to the character q.
indexOf()This method returns the index of the specified character when it first occurred in the string.
let str = "abcba";
console.log(str.indexOf("b")); // -> 1Notice that even though b occurred twice in the string, only one value is returned.
lengthlength is not just a method, it is a getter method. We will talk about their differences later in the objects lesson.
For now, you only need to know that it returns the number of characters in the string.
let str = "abcba";
console.log(str.length); // -> 5slice()The slice() method extracts a part of the string based on the given indexes.
let str = "qwerty";
// Extract characters between index 1 (inclusive) and index 3 (exclusive).
console.log(str.slice(1, 3)); // -> we
// Extract characters from index 2 to the end
console.log(str.slice(2)); // -> ertysplit()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 in practice.
For example, if given a URL, you can use the split() method to extract the slug.
let url = "https://thedevspace.io/course/javascript-strings";
let arr = url.split("/");
console.log(arr); // -> [ 'https:', '', 'thedevspace.io', 'course', 'javascript-strings' ]
let slug = arr[4];
console.log(slug); // -> javascript-stringstoLowerCase() and toUpperCase()These are two similar methods that convert the string into lower or upper letters, respectively.
let str = "Qwerty";
console.log(str.toLowerCase()); // -> qwerty
console.log(str.toUpperCase()); // -> QWERTYtrim()Returns a string with the leading and tailing white spaces removed.
let str =
"\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";
console.log(str.trim());Lorem ipsum dolor sit amet consectetur adipisicing elit.
Assumenda, quaerat perferendis nam vitae harum iusto repellendus suscipit, ipsa fugit aliquid sapiente modi non qui doloremque inventore.
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.
console.log("Hello, World!");