A JavaScript string is any sequence of characters enclosed in single, double, or backtick quotes.
const doubleQuotedString = "This is a double quoted string";
const singleQuotedString = 'This is a single quoted string';
const backtickQuotedString = `This is a string wrapped in backticks`;
There is no difference between single quotes and double quotes, and there are two peculiarities of backticks.
Template strings
Template strings are the first useful feature of strings wrapped in backticks. Do you remember the task where we greeted the user and substituted their name in the string? Using template strings, the solution would look like this:
const sayHello = (name) => {
return `Hello, ${name}!`;
}
If a string with backticks contains the construction ${}
, then the expression inside curly braces will be calculated
and then placed into the final string. The expression can be not only a variable but also any other valid JS code.
Arithmetic operations, calls to other functions, everything goes.
Using template strings is more convenient and easy than string concatenation with +
, especially if you need to come
up with a string with many parameters.
Multiline strings
Also, with backticks, you can create a string that will appear on multiple lines on the screen.
const multiLineString = `This string consists
of
multiple
lines.
You can try to print the "multiLineString" to the screen with console.log
to make sure it's true.
`;
Again, all text data in JavaScript is treated as strings. Even if your string doesn’t have a single character, it’s still a string. It doesn’t matter if it consists of a single character or ten thousand, one line, or three hundred lines - this is always a string if it is wrapped in quotes.
Similarities between strings and arrays
At its core, a string is an array of characters. Like an array, it has a length
property. It stores the length
of the string. Also, as with an array, elements can be accessed by index using the square brackets []
after the
name of the string.
const welcomeMessage = 'Hi!';
const goodbyeMessage = 'Bye!';
console.log(welcomeMessage.length); // 3
console.log(goodbyeMessage.length); // 4
console.log(welcomeMessage[0]); // H
console.log(goodbyeMessage[2]); // e
But there is one huge difference between strings and arrays.
Strings in JS are immutable.
You can add a new element to the array or replace an existing one using the assignment operator =
. But, if you try
to do the same with a string, you’ll fail.
const arr = [1, 2, 3, 4];
arr.push(5);
arr[2] = 0;
console.log(arr); // [1, 2, 0, 4, 5]
const s = '1234';
s[2] = '0';
console.log(s); // 1234
The immutability of strings is a very important concept. Next, we’ll look at some functions that “seem” to modify a
string, such as replace
or slice
, but in reality, they just create a new string and the original one remains
unchanged.
Useful built-in string functions
All JS strings belong to the same String data type and contain several useful functions. They are all built into the String type and can be called on all objects of that type.
Function | Description |
---|---|
includes(substring) | Search for a substring. Returns true if a match is found, otherwise false . |
endsWith(substring) | Determines if a string ends with substring . Returns true or false . |
indexOf(substring) | Returns the index of the first occurrence of substring in the string, or -1 if it’s not found. |
replace(s1, s2) | Replaces all occurrences of s1 with s2 in the original string and returns the result |
split(separator) | Splits the string into an array of strings by separator which is a string too. Example: 'hello world !'.split(' ') will be evaluated to ['hello', 'world', '!'] |
These are just some of the functions that will help us interact with strings. For a complete list and description, visit our knowledge base at learn.coderslang.com.
Special characters
In addition to the regular letters and numbers, strings can include special characters. Perhaps the most commonly
used character is \n
- the newline character. If it appears in a string, then the string will be split in two, and
the part that comes after \n
will appear on a new line.
const twoLineString = 'This string consists of \n two lines';
const multilineString = 'This string \n has \n even more \n lines, \n as there are more \n newline chars';
If we print the strings twoLineString
and multilineString
to the console, the first will take two lines, and
the second will take five.
Besides, you can add characters to the string that are not available on a conventional keyboard, such as emoticons.
const stringWithAHappyFace = 'I like to smile \u263A!' // I like to smile ☺!
const checkmarkString = '\u2714 DONE'; // ✔ DONE
const failedTask = '\u2B55 FAIL'; // ❌ FAIL
Special characters occur in several formats. In the above example, you saw UTF-16. It consists of four hexadecimal
digits (0, 1, … F) preceded by \u
.
At some point, there we ran out of UTF-16 chars and created a new format - ** UTF-32 **. The general formula is
similar. It starts with \u
, but a further sequence of hexadecimal digits is enclosed in curly braces.
Giving us something like \u{1f44d}
or 👍 when printed to the screen.
It is pointless to memorize all these codes, just know that they exist and if you need them you can easily google them. Here is a site with a list of all the special characters you can add to the string.
Escape characters
Displaying some characters is not as easy as it seems. For example, imagine that you want to print the string
'Your data is in the \new directory'
. If we just pass this line to console.log
, we get two lines printed
to the screen:
Your data is in the
ew directory
This happens because \n
was perceived as a single newline character. To solve this problem, you need to escape the
\
character. This can be done using one more \
placed in front of the character that we want to escape.
So, our line will change to 'Your data is in the \\new directory'
.
Another example would be the quotes. Imagine a string - 'I'm a Full Stack JS Engineer, I can use symbols like "", ``, '' in any string'
. Again, you can’t just save it to a variable and expect everything to be fine.
You need to “tell the computer” that some characters in the string should be treated differently than usual.
const incorrectString = 'I'm a Full Stack JS Engineer, I can use symbols like "", ``,'' in any string';
const fixedString = 'I\'m a Full Stack JS Engineer, I can use symbols like "", ``, \'\' in any string';
In the first case, the computer “thinks” that the string ends after the second single quote, and then an
incomprehensible set of characters follows. By adding \
before the character '
, we escaped it, that is,
we “told” the computer that this character is part of a string and should be displayed exactly as it appears.
Converting a string into a number
In one of the first lectures, you learned that '123'
and 123
are different. The first one is a string, and
the second one is a number. They look almost the same, but they are of different types, thus behave differently.
There are often situations when we need to convert a string to a number or vice versa. To do this, we need the
functions String(value)
and Number(value)
.
const unformattedPrice = '1100 USD';
const normalPrice = 20;
Now we’re in a situation where we need to extract the numeric part from the string unformattedPrice
and add it
with normalPrice
. If we try to do just unformattedPrice + normalPrice
, the result will be the string 1100 USD20
.
The number will be converted to a string and the two strings will be glued together.
The first step we need to take is to extract the numeric part from the unformattedPrice
string. Let’s use the
replace
function and get:
const unformattedPrice = '1100 USD';
const normalPrice = 20;
const formattedPrice = unformattedPrice.replace ('USD', '');
console.log (formattedPrice); // 1100
console.log (formattedPrice + normalPrice); // 110020
Remember that the strings are not changed and the replace
function will return us a new string, which we will
store in the formattedPrice
constant. But this is only half the battle. formattedPrice
is still a string,
and the result is 110020
instead of the expected 1120
.
const unformattedPrice = '1100 USD';
const normalPrice = 20;
const formattedPrice = unformattedPrice.replace ('USD', '');
const formattedConvertedPrice = Number (formattedPrice);
console.log (normalPrice + formattedConvertedPrice);
Now everything is in place. We passed the value '1100'
to the Number
function, which did a string to number
conversion for us. Now in formattedConvertedPrice
there is a number that we can add to normalPrice
and
display the result on the screen for verification.
The code above can be simplified to three lines:
const unformattedPrice = '1100 USD';
const normalPrice = 20;
console.log (normalPrice + Number (unformattedPrice.replace ('USD', '')));
To understand other rules for converting types and arithmetic operations in JS - read this article.
FAQ
— How to change the character of a string knowing its position?
—JS strings are immutable. This means that it is impossible to change the chars inside of it, but you can create a
new one, which will contain all the necessary changes.
— Will the command console.log(${2 + 2})
display 4 and not 22?
— Yes, it will.
— What happens if I pass some random string into the function Number()
, i.e. do something like Number('hello')
?
— It’s a great question. The result will be NaN
. It’s a special value that is generated whenever the result of
the numerical operation can’t be determined.
— What does NaN mean?
— Not a Number