This tutorial is first published at FreeCodeCamp.
String manipulation is a common task for programmers, whether it is extracting information from the string, converting letter cases, joining strings, or trimming extra white spaces.
This tutorial covers various methods and techniques for manipulating strings using JavaScript, offering you a comprehensive guide on how to work with strings in your JavaScript applications.
How to extract a character from string
Let's start by talking about how to extract a single character from a string. JavaScript offers three different methods for this purpose: charAt()
, at()
, and charCodeAt()
.
charAt(index)
The charAt()
method accepts an index, and returns the character at that index.
1const str = "Hello World!";
2
3console.log(str.charAt(0));
4console.log(str.charAt(8));
5console.log(str.charAt(16));
1H
2r
3
If the index is out of range, charAt()
will return an empty string (""
).
at(index)
The at()
method is added to JavaScript with ES2022, and it is very similar to charAt()
. You pass it an index, and the method returns the character at that index.
1const str = "Hello World!";
2
3console.log(str.at(0));
4console.log(str.at(8));
5console.log(str.at(16));
1H
2r
3undefined
When the index is out of range, at()
will return undefined
instead of an empty string.
Another difference is that at()
allows for negative indexing, meaning index -1
returns the last character of the string, -2
returns the second last character, and so on.
1const str = "Hello World!";
2
3console.log(str.at(-1));
4console.log(str.at(-2));
1!
2d
Before at()
, the only way to do this is through the length
property.
1const str = "Hello World!";
2
3console.log(str.charAt(str.length - 1)); // The last character
4console.log(str.charAt(str.length - 2)); // The second last character
1!
2d
charCodeAt(index)
The charCodeAt()
method returns the UTF-16 code of the character at the specified index.
1const str = "Hello World!";
2
3console.log(str.charCodeAt(0));
4console.log(str.charCodeAt(4));
172
2111
How to extract a substring
Besides extracting a single character, JavaScript also allows you to extract a substring using methods substring()
and slice()
.
substring(start, end)
substring()
extracts a substring based on the provided start
(inclusive) and end
(exclusive) indexes, and returns the substring as a new string.
1const str = "JavaScript";
2
3console.log(str.substring(0, 4));
1Java
The end
index can be left out, in which case the substring will extracted from start
to the end of the string.
1const str = "JavaScript";
2
3console.log(str.substring(4));
1Script
slice(start, end)
slice()
is very similar to substring()
. It also extracts a substring based on the provided start
and end
indexes, and returns the substring as a new string.
1const str = "JavaScript";
2
3console.log(str.slice(0, 4));
1Java
The end
index can also be omitted.
1const str = "JavaScript";
2
3console.log(str.slice(4));
1Script
The difference is that slice()
accepts negative indexes. For example, the following example extracts the substring from index -10
to -6
.
1const str = "JavaScript";
2
3console.log(str.slice(-10, -6));
1Java
How to convert string to upper and lower cases
The methods toUpperCase()
and toLowerCase()
converts the string to upper or lower cases.
1const str = "JavaScript";
2
3console.log(str.toUpperCase());
4console.log(str.toLowerCase());
1JAVASCRIPT
2javascript
How to join two strings together
The easiest way to join two strings together is using the +
operator:
1const str1 = "Hello";
2const str2 = "World!";
3
4const str3 = str1 + " " + str2;
5
6console.log(str3);
1Hello World!
Alternatively, you can use the concat()
method:
1const str1 = "Hello";
2const str2 = "World!";
3
4const str3 = str1.concat(" ", str2);
5
6console.log(str3);
1Hello World!
Or the template literals:
1const str1 = "Hello";
2const str2 = "World!";
3
4const str3 = `${str1} ${str2}`;
5
6console.log(str3);
1Hello World!
How to trim extra white spaces from string
When working with strings that came from external sources, such as parsed from a webpage or received from user input, a common problem you might encounter is the leading and trailing white spaces.
JavaScript offers three different methods that allow you to easily remove the extra white spaces and keep only the useful information.
The trimStart()
method removes the leading white spaces, including spaces, tabs, and line breaks. The trimEnd()
method removes trailing white spaces, and trim()
removes white spaces from both ends.
1const str = " \n\tHello World!\t\n ";
2
3console.log(str.trimStart());
4console.log(str.trimEnd());
5console.log(str.trim());
1Hello World!
2
3
4 Hello World!
5Hello World!
How to add padding to string
The methods padStart()
and padEnd()
can be used to pad characters or substrings to the beginning or the end of the original string.
Both methods take two arguments, length
and a substring. The substring will be repeated multiple times, until the resulting string reaches the target length.
1const str = "123";
2
3console.log(str.padStart(5, "0"));
4console.log(str.padEnd(5, "0"));
100123
212300
If the substring is causing the resulting string to exceed the target length, then only a part of that substring will be used.
1const str = "123";
2
3console.log(str.padStart(8, "ok"));
1okoko123
Notice that the substring "ok"
is repeated twice, but for the third time, it causes the resulting string to exceed the length limit, so only "o"
is used for the final padding.
How to repeat a string
The repeat()
returns a new string, with the specified number of copies of the original string.
1const str = "123";
2
3console.log(str.repeat(3));
1123123123
How to split string into an array
The split()
method splits the string based on the given character, and returns the result in an array. This method is most useful when you need to extract information from a URL. For example, this is how you can extract the slug of a blog post:
1const url = "http://www.example.com/blog/example-article";
2
3let arr = url.split("/");
4console.log(arr);
5
6let slug = arr[4];
7console.log(slug);
1[ 'http:', '', 'www.example.com', 'blog', 'example-article' ]
2example-article
How to search in a string
You can also search for a character or substring using JavaScript.
indexOf()
andlastIndexOf()
The indexOf()
method returns the index of the first occurrence of the given character.
The lastIndexOf()
methods returns the index of the last occurrence of the given character.
1const str = "Hello World";
2
3console.log(str.indexOf("l"));
4console.log(str.lastIndexOf("l"));
12
29
Both methods will return -1 if a match is not found.
1const str = "Hello World";
2
3console.log(str.indexOf("x"));
4console.log(str.lastIndexOf("x"));
1-1
2-1
includes()
The includes()
method tests if the string contains the given character or substring. It returns true
if the substring is found, otherwise false
will be returned.
1const str = "JavaScript";
2
3console.log(str.includes("S"));
4console.log(str.includes("Script"));
5console.log(str.includes("script"));
1true
2true
3false
startsWith()
andendsWith()
As the name suggests, these two methods test if the given substring is found at the beginning or the end of the string.
1const str = "JavaScript";
2
3console.log(str.startsWith("Java"));
4console.log(str.endsWith("Java"));
5
6console.log(str.startsWith("Script"));
7console.log(str.endsWith("Script"));
1true
2false
3false
4true
How to search in a string using Regex
However, what if you need something more powerful? For example, the indexOf()
and lastIndexOf()
methods only return the first and last occurrences of the substring, but what if you need to search for all of them?
Or what if, instead of a substring, you need to search for a pattern, such as a phone number or a price tag?
This can be achieved by combining the string methods with Regex, which stands for regular expression. It is a programming tool that allows you to describe patterns in a string. Regex has a very cryptic syntax, but can be very useful sometimes.
search()
The search()
method works similarly to indexOf() we just discussed. It also returns the first occurrence of the matched substring or pattern, except that search()
allows you to pass a regular expression.
The following example, /(?<=\$)\d\d?\d?\d?/
, searches for a price tag in the string, which should start with a dollar sign ($
), and followed by 1 to 4 numeric digits.
1const str = "The laptop costs $1500. The tablet costs $1000.";
2
3console.log(str.search("1500"));
4console.log(str.search(/(?<=\$)\d\d?\d?\d?/));
5console.log(str.search(/(?<=\$)\d\d?\d?\d?/g));
118
218
318
Notice that the global flag (g
) has no effect on search()
, and it still returns the first occurrence of the match.
match()
andmatchAll()
Compared to search()
, the match()
method returns much more information that you can work with, such as the actual substring that matches the pattern, the index where the match is found, and more.
1const str = "The laptop costs $1500. The tablet costs $1000.";
2
3console.log(str.match(/(?<=\$)\d\d?\d?\d?/));
4console.log(str.match(/(?<=\$)\d\d?\d?\d?/g));
1[
2 '1500',
3 index: 18,
4 input: 'The laptop costs $1500. The tablet costs $1000.',
5 groups: undefined
6]
7[ '1500', '1000' ]
By including a global flag, you can make match()
return all matched substrings, instead of just the first one.
There is also a matchAll()
method that forces you to use the global flag. Without it, the method will return a TypeError
.
matchAll()
will return a iterable object, which you can iterate over using a for of
loop.
1const str = "This laptop costs $1500. The tablet costs $1000.";
2
3const prices = str.matchAll(/(?<=\$)\d\d\d\d/g);
4
5for (let price of prices) {
6 console.log(price);
7}
1[
2 '1500',
3 index: 19,
4 input: 'This laptop costs $1500. The tablet costs $1000.',
5 groups: undefined
6]
7[
8 '1000',
9 index: 43,
10 input: 'This laptop costs $1500. The tablet costs $1000.',
11 groups: undefined
12]
How to replace a string pattern
Lastly, the replace()
method allows you to match for a pattern, and then replace the matched substrings with a new string. For example,
1const str = "JavaScript javaScript Javascript";
2
3console.log(str.replace(/JAVASCRIPT/i, "javascript"));
4console.log(str.replace(/JAVASCRIPT/gi, "javascript"));
1javascript javaScript Javascript
2javascript javascript javascript
By default, replace()
only matches and replaces the first occurrence of the pattern, but with the global flag, you can replace all matched patterns.
Conclusion
In this tutorial, we explored various methods you can use to work with strings in JavaScript, and also covered how to use regular expressions to match for string patterns.
As a brief summary, here are the methods we discussed in this tutorial:
charAt(index)
: Extracts the character at the specified index from a string.at(index)
: Retrieves the character at the specified index, supports negative indexing.charCodeAt(index)
: Returns the UTF-16 code of the character at the specified index.substring(start, end)
: Extracts a part of the string between the start (inclusive) and end indexes (exclusive).slice(start, end)
: Similar tosubstring()
, extracts a part of the string between start (inclusive) and end indexes (exclusive), but supports negative indexing.toUpperCase()
: Converts all letters in the string to uppercase.toLowerCase()
: Converts all letters in the string to lowercase.concat()
: Joins two or more strings together.trimStart()
: Removes whitespace from the beginning of a string. Including spaces, tabs, and newlines.trimEnd()
: Removes whitespace from the end of a string.trim()
: Removes whitespace from both ends of a string.padStart(length, substring)
: Pads the start of a string with another string (multiple times, if needed) until the resulting string reaches the given length.padEnd(length, substring)
: Pads the end of the string with another string (multiple times, if needed) until the resulting string reaches the given length.repeat(count)
: Returns a new string which contains the specified number of copies of the original string.split(separator)
: Splits the string into an array of substrings, using the specified separator to determine where to make the split.indexOf(searchValue)
: Returns the index of the first occurrence of the specified substring. Returns -1 if not found.lastIndexOf(searchValue)
: Returns the index of the last occurrence of the specified substring. Returns -1 if not found.includes(searchValue)
: Determines whether the string contains the specified substring, returningtrue
orfalse
.startsWith(searchValue)
: Checks if the string begins with the specified substring.endsWith(searchValue)
: Checks if the string ends with the specified substring.search(regexp)
: Search for a string pattern, which could be defined by a Regex. Returns the index of the first occurrence of the match or -1 if not found.match(regexp)
: Search for a string pattern, which is defined by a Regex. If a global flag is included, it will return all occurrences of the pattern.matchAll(regexp)
: Returns an iterable object containing all results matching a string against a global regular expression.replace(regexp, newSubstr)
: Replaces occurrences of a pattern (specified by a regular expression) with a new substring.
If you want to learn more about JavaScript and web development, check out my new course at TheDevSpace.io.