The JavaScript String Handbook – How to Work With Strings in JS
The JavaScript String Handbook – How to Work With Strings in JS
Table of Contents
1. What are Strings in JavaScript
3. Template Literals
– Basic usage
– Multiline strings
– Expression evaluation
– Tagged templates Forum Donate
– Use cases
Learn to code — free 3,000-hour curriculum
4. The String Constructor
– Using the Strings Constructor
– String objects vs. string primitives
– Converting string objects to primitives
– Rare use cases
6. Concatenation
– Using the + operator
– Using the concat method
– Concatenating Variables and Strings
– Combining String.fromCharCode with Concatenation
7. Characteristics of Strings
– Immutability
– Sequence of characters
Single Quotes
Escaping Quotes
If you need to include a quote character within a string that is enclosed
by the same type of quote, you can use the backslash ( \ ) as an escape
character:
While you can freely switch between single and double quotes, even
within the same project, like this:
Forum Donate
Template Literals
Template literals, introduced in ECMAScript 6 (ES6), provide a more
powerful and flexible way to create strings in JavaScript. They offer
improved syntax for embedding variables and expressions within
strings, making the code more concise and readable.
Basic Usage
In this example, the string is defined using backticks ( `), and the
variable name is embedded within the string using ${}`. This
syntax allows you to seamlessly include variables and expressions
directly in the string.
Multiline Strings
Template literals also support multiline strings, making it more
convenient to represent multiline text without resorting to
concatenation or special characters:
const multilineString = `
This is a multiline
string using template literals.
`;
console.log(multilineString);
/*
Output:
This is a multiline
string using template literals.
*/
Expression Evaluation
Expressions within ${} are evaluated, allowing for more complex
expressions and calculations within the string:
const num1 = 5;
Forum Donate
const num2 = 10;
Learn to code — free 3,000-hour curriculum
const result = `The sum of ${num1} and ${num2} is ${num1 + num2}.`;
Tagged Templates
Template literals can also be used with a function, known as a "tag
function," allowing for more advanced string processing. The function
receives the string parts and values as separate arguments, enabling
custom string manipulation:
Use Cases
Dynamic String Creation
Template literals are especially useful when creating strings
Forum Donate
dynamically based on variables or expressions:
Learn to code — free 3,000-hour curriculum
HTML Templates
Template literals are commonly used in frontend development for
creating HTML templates dynamically:
const htmlTemplate = `
<div class="item">
<h2>${itemName}</h2>
<p>${itemDescription}</p>
</div>
`;
Basic Usage
In this example, the Unicode values 72 , 101 , 108 , 108 , and 111
correspond to the characters H , e , l , l , and o , respectively. The
String.fromCharCode method takes these values as arguments and
returns a string composed of the corresponding characters.
Use Cases:
Generating Strings with Specific Characters
Concatenation
Concatenation is a fundamental string operation in JavaScript that
involves combining two or more strings into a single string. This
process allows you to build longer strings by appending or joining
existing ones. In JavaScript, concatenation can be achieved using the
+ operator or the concat method.
In this example, the strings John and Doe are concatenated with a
space in between to form the full name John Doe .
In this example, the Unicode values for H and e are combined with
the string llo using the + operator.
Characteristics of Strings
Immutability
Immutability in JavaScript strings means that once a string is created,Donate
Forum
its content cannot be changed. Operations like concatenation or
Learn to code — free 3,000-hour curriculum
changing case create new strings, leaving the original string
unmodified. This concept ensures predictability, simplifies debugging,
and aligns with functional programming principles.
// Outputting results
console.log('Original String:', originalString);
console.log('Concatenated String:', newString);
console.log('Uppercase String:', upperCaseString);
console.log('Substring:', substring);
Also, you may have noticed some string methods like toUpperCase()
and slice() in the examples above. You'll learn more about those in
the upcoming sections.
Sequence of Characters
A sequence of characters in JavaScript refers to a linear arrangement
of individual characters that form a string. A character sequence can
include letters, numbers, symbols, and whitespace. Each character in
the sequence has a specific index or position, starting from 0 :
toLowerCase()
Conversely, the toLowerCase() method converts all characters in a
string to lowercase:
trim()
The trim() method removes whitespaces from both ends of a string
and returns the result:
trimStart()
The trimStart() method (also known as trimLeft() ) removes
whitespaces from the beginning (start) of a string:
trimEnd()
The trimEnd() method (also known as trimRight() ) removes
whitespaces from the end of a string:
Note: These methods do not modify the original string. Instead, they
return a new string with the whitespaces removed. This is consistent
with the immutability concept in JavaScript strings.
String Searching
indexOf() and lastIndexOf()
The indexOf() method is used to find the first occurrence of a
substring within a string. If the substring is not found, it returns -1 :
The lastIndexOf() method works similarly but starts the search from
the end of the string, allowing for reverse searching.
The includes() Method for Substring Forum Donate
Presence Learn to code — free 3,000-hour curriculum
The includes() method simplifies the task of checking whether a
string contains a specific substring, returning a boolean value:
These methods are commonly used for file type validation and similar
tasks.
string.slice(startIndex, endIndex);
substring() Method:
The substring() method is similar to slice() but has a different
syntax. It extracts a specified portion of a string but does not support
negative indices. Here's the syntax: Forum Donate
string.substring(startIndex, endIndex);
Modifying Strings
Replacing Substrings with replace()
The replace() method is instrumental in replacing a specified
substring with another string. This is particularly useful for updating
content dynamically: Forum Donate
String Comparison
Equality Checks with === and ==
In JavaScript, comparing strings involves the use of the === and ==
operators. The === operator checks both the value and the type,
ensuring a strict equality check:
On the other hand, the == operator checks for equality with type
coercion:
In this example, the regular expression /at/g uses the global flag, g ,
and searches for occurrences of at in the string.
search()
The search() method returns the index of the first match of a regular
expression in a string. If no match is found, it returns -1 :
const sentence = "The cat and the hat";
Forum Donate
const index = sentence.search(/at/); // 7
Learn to code — free 3,000-hour curriculum
In this case, the regular expression /at/ is searching for the first
occurrence of at in the string.
replace()
The replace() method is used to replace occurrences of a substring
or pattern with another string. Regular expressions enhance its
capabilities, allowing for more complex replacements:
This loop correctly iterates over both characters in the string, even
though 𝒜 is outside the BMP.
Use Cases
Multilingual Support: Unicode enables JavaScript to handle
text in various languages and writing systems, allowing for the
creation of multilingual applications.
const num = 5;
const str = '10';
const num = 5;
const str = '10';
Suppose you'reLearn
building a form
to code that
— free requires acurriculum
3,000-hour user to enter their
email address. To validate the input, you can use string methods:
function validateEmail(email) {
// Check if the email contains the @ symbol
if (!email.includes('@')) {
return false;
}
// Check if the email ends with a valid domain (e.g., .com, .org)
const domain = email.split('@')[1];
const validDomains = ['com', 'org', 'net'];
if (!validDomains.includes(domain.split('.')[1])) {
return false;
}
return true;
}
Formatting Names
Suppose you have a list of names in the format "First Last" and you
want to display them as "Last, First." You can achieve this with string
manipulation:
function formatNames(names) {
return names.map((name) => {
const [first, last] = name.split(' ');
return `${last}, ${first}`;
});
Forum Donate
}
Learn to code — free 3,000-hour curriculum
const originalNames = ['John Doe', 'Jane Smith', 'Bob Johnson'];
const formattedNames = formatNames(originalNames);
console.log(formattedNames);
// Output: ['Doe, John', 'Smith, Jane', 'Johnson, Bob']
Conclusion
In this article, we covered the fundamentals of working with strings in
JavaScript. We explored basic operations such as concatenation and
finding the length of a string. Additionally, we delved into various
string methods for changing case, extracting substrings, finding
substrings, replacing substrings, and splitting strings.
If you read this far, thank the author to show them you care.
Say Thanks
Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers,
services, and staff.
Mobile App
Our Charity
About Alumni Network Open Source Shop Support Sponsors Academic Honesty