Work With Strings in JavaScript II
17 min read·Jan 1, 2026
In JavaScript, string primitives declared as string literals using single quotes '' and double quotes "" are automatically wrapped in the String object, allowing you to use object-specific properties and methods.
Getting the length of strings
To get the number of characters of a string (its length), you can use its length property:
string.length
Example
Let's consider this script, that filters an array based on the length of its string values:
const fruits = [
'banana',
'apple',
'pineapple',
'raspberry',
'orange',
'lemon'
];
console.log(fruits.filter(fruit => fruit.length <= 5));
When executed, it will use the filter() method of the fruits array to filter out the strings whose length property is greater than or equal to 5 characters.
Which will produce this output:
[ 'apple', 'lemon' ]
Searching and replacing substrings
To check whether a string includes a substring, you can use its includes() method:
let exists = string.includes(substring);
Alternatively, to check whether a string starts or ends with a substring, you can use the startsWith() and endsWith() methods:
let exists = string.startsWith(substring);
let exists = string.endsWith(substring);
Note: All three methods return
trueif the substring exists, andfalseotherwise.
Example
Let's consider these statements, that all evaluate to true:
let string = 'Hello, world!';
string.includes('world') // true
string.startsWith('H') // true
string.endsWith('ld!') // true
As the string "Hello, world!":
- Includes the substring
"world". - Starts with the letter
"H". - Ends with the substring
"ld!".
Finding the position of substrings
To find the index of the first character of the first occurrence of a substring, you can use the indexOf() method:
let index = string.indexOf(substring);
On the other hand, to find the index of the last occurrence, you can use the lastIndexOf() method:
let index = string.lastIndexOf(substring);
Example
Let's consider this script:
let string = "Hello, world!";
string.indexOf("o"); // 4
string.lastIndexOf("o"); // 8
When executed:
- The
indexOf()method will return4, which is the position of the letter'o'in the word'Hello'. - The
lastIndexOf()method will return8, which is the position of the letter'o'in the word'world':
Replacing a substring
To replace the first occurrence of a substring and return a new string, you can use the replace() method:
let newString = string.replace(substring, newSubstring);
Alternatively, to replace all occurrences of a substring and return a new string, you can use the replaceAll() method:
let newString = string.replaceAll(substring, newSubstring);
Example
Let's consider this script, that replaces all occurrences of a character in a string:
const lowercase = 'Hello, world!';
const uppercase = lowercase.replaceAll('l', 'L');
console.log(uppercase);
When executed, it will use the replaceAll() method of the lowercase string to replace all the occurrences of the lowercase character 'l' with the uppercase character 'L'.
Which will produce this output:
HeLLo, worLd!
Extracting a substring
To extract a part of a string as a new string, you can use the slice() method:
let substring = string.slice(start, end?);
Where:
startis the index of the first character to include in the substring.endis the optional index of the first character to exclude from the substring.
Note: When using negative indexes, the
slice()method will extract starting from the end of the string, whose last character is at index-1.
Example
Let's consider this script, that extracts the same substring using different indexes:
const string = "Hello, world!";
const substrA = string.slice(7, string.length - 1);
const substrB = string.slice(-6, -1);
console.log(substrA);
console.log(substrB);
Which will produce this output:
world
world
Splitting and joining strings
Splitting strings
To split a string into an array of substrings, you can use the split() method as follows:
let strings = string.split(separator);
Where separator is a substring used to delimit the chunks.
Example
📚 Definition: The comma-separated values format (CSV) is an inline data format where columns are separated by commas
,and rows are terminated by newlines\n.
Let's consider this script, that parses a CSV input:
const csv = "id,email,name\n1,johndoe@mail.com,John Doe\n2,adoe@mail.com,Alice Doe";
const rows = csv.split('\n');
for (let row of rows) {
let [id, email, name] = row.split(',');
console.log(id, email, name);
}
When executed, it will:
- Split the string contained in the
csvvariable into an array of strings using\nas a delimiting character. - Iterate on each element of the
rowsarray using afor...ofloop. - Split the string contained in the
rowvariable into an array of strings using,as a delimiting character. - Output the value of each individual destructured column.
Which will produce this output:
id email name
1 johndoe@mail.com John Doe
2 adoe@mail.com Alice Doe
Joining strings
To join the elements of an array of strings into a single string, where each element is separated by a substring, you can use the join() method:
let string = strings.join(separator);
Tip: You can use an empty string
''as a separator to join the strings of the array back to back.
Example
Let's consider this script, that convert an array of strings into a single CSV-formatted string:
const data = [
['id', 'email', 'name'],
[1, 'johndoe@mail.com', 'John Doe'],
[2, 'adoe@mail.com', 'Alice Doe']
];
let csv = data.map(row => row.join(',')).join('\n');
console.log(csv);
When executed, it will:
- Use the
map()method of thedataarray to transform each element of each row into a comma-separated string using itsjoin(',')method. - Use the
join('\n')method of the resultingdataarray to join each row into a newline-separated string.
Which will produce this output:
id,email,name
1,johndoe@mail.com,John Doe
2,adoe@mail.com,Alice Doe
Tagged templates
A tagged template is an advanced form of template literal that allows you to parse its content using a regular function:
function tag(strings, ...placeholders) {
//
}
const result = tag`word1 ${placeholder1} word2 ${placeholder2}`;
Where:
stringsis an array containing the string literal chunks of the template literal (e.g.,"word1","word2", etc)....placeholdersis an array containing the value of the placeholders of the template literal (e.g.,placeholder1,placeholder2, etc).
Note: The signature of the tag function can also be written as follows:
function tag(strings, placeholder1, placeholder2, ...) { // }
Example
Let's consider this script:
function total(strings, ...numbers) {
const sum = numbers.reduce((acc, cur) => {
acc += cur;
return acc;
}, 0);
return `${strings[0]}${sum}`;
}
console.log(total`It costs ${2} + ${3} + ${4}`);
When executed, it will calculate the sum of all placeholders of the template literal using the total() function and return a string containing the first chunk of the template concatenated to the value of the sum variable.
Which will produce this output:
It costs 9
Summary
Here's a summary of what you've learned in this lesson:
- The
lengthproperty is used to get the length of a string. - The
charAt()method is used to access an individual character of a string. - The
includes()method is used to check if a string contains a substring. - The
startsWith()andendsWith()methods are used to check if a string starts or ends with a substring. - The
indexOf()andlastIndexOf()methods are used to return the index of the first and last occurrence of a substring. - The
replace()method is used to replace the first occurrence of a substring and return a new string. - The
replaceAll()method is used to replace all the occurrences of a substring and return a new string. - The
slice()method is used to extract a substring. - The
split()method is used to split a string into an array of string based on a delimiter. - The
join()method is used to join an array of strings into a single string using a delimiter. - The
concat()method is used to join two or more strings.
Enjoying the courses?
I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:
Support BackendBrewery