In JavaScript, the strings are used for storing and manipulating text. No separate type exists for a single character. The strings internal format is always UTF-16.
A string represents zero or more characters that are written inside quotes.
Popular String Functions
Function | Description |
---|---|
charAt(index) | Returns the character at the specified index. |
charCodeAt(index) | Returns the Unicode of the character at the specified index. |
concat(...strings) | Concatenates the string arguments to the calling string and returns a new string. |
includes(searchString, position) | Determines whether the calling string contains the searchString . |
indexOf(searchValue, fromIndex) | Returns the index of the first occurrence of searchValue in the string, starting the search at fromIndex . Returns -1 if the value is not found. |
lastIndexOf(searchValue, fromIndex) | Returns the index of the last occurrence of searchValue within the calling string, searching backwards from fromIndex . Returns -1 if the value is not found. |
match(regexp) | Retrieves the matches when matching a string against a regular expression. |
matchAll(regexp) | Returns an iterator of all results matching a string against a regular expression, including capturing groups. |
repeat(count) | Returns a new string consisting of the calling string repeated count times. |
replace(searchFor, replaceWith) | Replaces the first match of a substring or pattern with a replacement string. |
replaceAll(searchFor, replaceWith) | Replaces all matches of a substring or pattern with a replacement string. |
search(regexp) | Searches the string for a match against a regular expression, and returns the index of the match. |
slice(startIndex, endIndex) | Extracts a section of a string and returns it as a new string, without modifying the original string. |
split(separator, limit) | Divides a string into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern; where the pattern is provided as the first parameter in the method's call. |
startsWith(searchString, position) | Determines whether the calling string begins with the characters of searchString . |
substring(startIndex, endIndex) | Returns the part of the string between the start and end indexes, or to the end of the string. |
toLowerCase() | Returns the calling string value converted to lowercase. |
toUpperCase() | Returns the calling string value converted to uppercase. |
trim() | Trims whitespace from both ends of the string. |
trimStart() or trimLeft() | Trims whitespace from the beginning of the string. |
trimEnd() or trimRight() | Trims whitespace from the end of the string. |
valueOf() | Returns the primitive value of a String object. |
About Quotes
We can distinguish single quotes, double quotes, and backticks:
let single = 'single-quoted';
let double = "double-quoted";
let backticks = `backticks`;
Double and single quotes are the same. Anyway, backticks are different. You can use them for embedding any expression into the string by wrapping it in ${…} as follows:
One of the most crucial advantages of backticks is that they allow a string to span numerous lines like this:
But, note that single and double quotes will now work in this case. If you use them trying to apply multiple lines, an error will occur:
let guestList = "Guests: // Error: Unexpected token ILLEGAL
* John ";
Single and double quotes appeared earlier than the backticks. Thus the backticks are more functional.
You can also specify a “template function” before the first backtick. The syntax will look like this:
func `string`
As a rule, the func function is called automatically. It receives both the string and embedded expressions processing them. Using this feature, you can quickly implement custom templating. Anyway, developers rarely use it in practice.
Special Characters
You can create multiline strings with double and single quotes with the help \n, like this:
There exist other less common special characters.
Find some of them in the list below:
- \', \" these special characters are used for quotes
- \r - carriage return. This character is now used alone. A combination of two characters \r\n is used for representing a line break in Windows text files.
- \\ - backslash
- \t - tab
- \xXX - unicode character with a particular hexadecimal unicode XX
- \uXXXX - this is unicode symbol with the hex code XXXX in UTF-16 encoding. It must include exactly 4 digits.
Here are examples with unicodes:
Take into account that all special characters begin with a backslash. It is also known as an “escape character.”
You can also use it in case you wish to put a quote into the string.
Here is an example:
Also, consider that backslash is mainly used for correcting reading of the string by JavaScript, after which it disappears. In the string memory, you can’t find any \ . But when you need to show an actual backslash within the string, you should double it like in this example:
The String Length
The length property is used for finding the length of a string:
Take into account that \n is a special character. Hence the length should be 7.
Sometimes developers mistype this property by calling str.length() instead of just str.length. That will not work.
Accessing Characters
Square brackets[pos] are mainly used for getting a character at a position [pos]. You can do that by calling the str.charAt(pos) method, as well. The very first character should start from zero:
Modern developers prefer to use the square brackets, while the charAt is rarely used
Strings are Changeless
It is not possible to change the strings in JavaScript. Look at this example to make sure that it won’t work:
The common practice is creating a whole new string assigning it to str instead of the old one like this:
Case Changing
We can distinguish two methods of changing the case. Here they are:
In another scenario, if it a single character should be lowercase, use this method:
Looking for a Substring
Let’s discover the ways of searching for a substring inside a string.
str.indexOf
This is the first method that is used for searching for the substr in str. It starts from the particular position pos and returns that position at the time the match is found, or -1, in case nothing is found.
Let’s check out the following example:
str.lastIndexOf(substr, position)
This method searches from the end of a string to the beginning. The occurrences will be listed in the reverse order.
Consider a slight difficulty with indexOf inside the if test. It can’t be put in if in this way:
So, it is necessary to check for the -1, as follows:
Includes, startsWith, endsWith
The more contemporary method str.includes(substr, pos) is capable of returning true/false depending on whether there is substr in the str.
Act like in the example, if you need to test for the match not needing its position at the same time:
The second argument of str.includes is position you start searching from. Here is an example:
Getting a Substring
JavaScript includes three methods of getting a substring: substring, substr, and slice.
str.slice(start [, end])
This method is used for returning the part of the string from start to end.
For example:
If a second argument is absent, the slice will go until the end, like this:
For start/end you can also use negative values.
For instance:
str.substring(start [, end])
This method is used for returning the part of the string between the start and the end.
It looks much like slice. The most notable difference is that in the framework of this method, the start can be greater than the end.
For example:
str.substr(start [, length])
This method returns the part of the string from the start, with a particular length. It differs from the previous methods. This method will help you specify the length instead of the ending position.
For instance:
The first argument might be negative for counting from the end:
Comparison of the Strings
It is essential to know that strings should be compared character-by-character in alphabetical order.
It would be best if you also considered the following characteristics:
- A lowercase is bigger than the uppercase, like this:
Comparison in javascript stringsconsole.log('a' > 'Z'); // true
- Letters containing diacritical marks are considered “out of order.”
For example:
Now, let’s start reviewing the internal representation of strings in JavaScript.
In JavaScript, we encode all strings using UTF-16. It means that each of the characters has an appropriate numeric code.
str.codePointAt(pos)
It is used for returning the code for the character at position pos :
String.fromCodePoint(code)
Makes a character by the numeric code:
Unicode characters can also be added by their codes applying \u followed by the hex code.
For instance:
Let’s have a look at the characters with codes 65..220 and make a string of them:
Here, you can notice that capital characters go first, then several special characters, and finally, Ö at the end of the output.
Practice Your Knowledge
Quiz Time: Test Your Skills!
Ready to challenge what you've learned? Dive into our interactive quizzes for a deeper understanding and a fun way to reinforce your knowledge.