Strings are one of the most commonly used data types in JavaScript. They allow you to store and work with text, including names, messages, email addresses, product descriptions, and other textual information.
JavaScript provides several ways to create strings, access individual characters, find string length, combine text with variables, and manipulate text using built-in string methods.
In this tutorial, you will learn how to create strings, access characters using indexing, find string length, use template literals, and work with useful JavaScript string methods.
What Is a String in JavaScript?
A string is a sequence of characters used to represent text. In JavaScript, strings are primitive values and are commonly written inside single quotes, double quotes, or backticks.
For example:
const name = "Rahul";
const city = 'Hyderabad';
const message = `Welcome to JavaScript`;
console.log(name);
console.log(city);
console.log(message);
Output:
Rahul
Hyderabad
Welcome to JavaScript
In this example, name, city, and message contain string values.
JavaScript also supports other primitive types, such as numbers, booleans, undefined, null, bigint, and symbols. You can learn more in the JavaScript data types tutorial.
String Creation in JavaScript
You can create strings in JavaScript using single quotes, double quotes, or backticks.
Creating Strings Using Single Quotes
Place text inside single quotation marks (' ').
const name = 'Rahul';
const language = 'JavaScript';
console.log(name);
console.log(language);
Output:
Rahul
JavaScript
Single quotes are useful for creating simple text values.
Creating Strings Using Double Quotes
You can also place text inside double quotation marks (" ").
const message = "Welcome to Web4Learners";
const course = "JavaScript Tutorial";
console.log(message);
console.log(course);
Output:
Welcome to Web4Learners
JavaScript Tutorial
In most situations, single and double quotes behave the same way. Choose one style and use it consistently in your code.
Creating Strings Using Backticks
Backticks (` `) are used to create template literals. They support multiline text and embedded expressions.
const message = `Welcome to JavaScript`;
console.log(message);
Output:
Welcome to JavaScript
Template literals are especially useful when combining text with variables. You will learn more about them later in this tutorial.
Using Quotes Inside Strings
You can use one type of quotation mark inside a string created with another type.
const message1 = "It's a beautiful day";
const message2 = 'He said, "Hello!"';
console.log(message1);
console.log(message2);
Output:
It's a beautiful day
He said, "Hello!"
If you need to use the same quotation mark inside the string, you can escape it with a backslash (\).
const message = 'It\'s a beautiful day';
console.log(message);
Output:
It's a beautiful day
String Indexing in JavaScript
String indexing allows you to access an individual character in a string using its position.
JavaScript uses zero-based indexing, which means the first character has an index of 0, the second has an index of 1, and so on.
Consider this string:
const language = "JavaScript";
console.log(language[0]);
console.log(language[1]);
console.log(language[2]);
console.log(language[3]);
Output:
J
a
v
a
The character at index 0 is J, while the character at index 1 is a.
Accessing the First and Last Characters
You can use index 0 to access the first character. To access the last character, subtract 1 from the string’s length.
const language = "JavaScript";
console.log(language[0]);
console.log(language[language.length - 1]);
Output:
J
t
This approach works for strings of different lengths.
Accessing Characters Using charAt()
JavaScript provides the charAt() method to retrieve a character at a specified index.
const language = "JavaScript";
console.log(language.charAt(0));
console.log(language.charAt(4));
Output:
J
S
For an ordinary string, language[4] and language.charAt(4) both return "S".
One difference is that accessing an out-of-range index with square brackets returns undefined, while charAt() returns an empty string.
const language = "JavaScript";
console.log(language[20]);
console.log(language.charAt(20));
Output:
undefined
The second output is an empty string, so it appears as a blank line.
Looping Through String Characters
You can use a loop to access each character in a string.
const language = "Code";
for (let i = 0; i < language.length; i++) {
console.log(language[i]);
}
Output:
C
o
d
e
This technique is useful when processing text character by character.
Remember that JavaScript string indexing uses UTF-16 code units. For some Unicode characters, such as many emoji, one visible character can occupy two code units. For those cases, Array.from() or string iteration with for...of can be more suitable.
String Length in JavaScript
The length property returns the number of UTF-16 code units in a string. For ordinary English letters and digits, this usually matches the number of characters you see.
Syntax:
string.length
Example:
const language = "JavaScript";
console.log(language.length);
Output:
10
The string "JavaScript" contains ten characters, so its length is 10.
Finding the Length of Different Strings
const name = "Rahul";
const city = "Hyderabad";
const message = "Hello World";
console.log(name.length);
console.log(city.length);
console.log(message.length);
Output:
5
9
11
Spaces are included in the string length. Therefore, "Hello World" has eleven code units, including the space.
Checking Whether a String Is Empty
You can use the length property to check whether a string contains any code units.
const username = "";
if (username.length === 0) {
console.log("Username is empty");
} else {
console.log("Username is not empty");
}
Output:
Username is empty
For simple string validation, you can also check username === "". If you want to reject strings containing only spaces, use trim() before checking the length.
Template Literals in JavaScript
Template literals are strings written with backticks. They let you insert variables and expressions directly into text using ${...}. This feature is called string interpolation.
Using Variables in Template Literals
const name = "Rahul";
const age = 21;
const message = `My name is ${name} and I am ${age} years old.`;
console.log(message);
Output:
My name is Rahul and I am 21 years old.
JavaScript evaluates the expressions inside ${...} and inserts their results into the string.
Using Expressions in Template Literals
You can insert calculations and other expressions inside ${...}.
const price = 500;
const quantity = 3;
console.log(`Total price: ₹${price * quantity}`);
Output:
Total price: ₹1500
The expression price * quantity is evaluated before its result is inserted into the string.
Creating Multiline Strings
Template literals allow you to create multiline strings without adding newline escape characters manually.
const message = `Welcome to Web4Learners.
Learn JavaScript step by step.
Practice with examples.`;
console.log(message);
Output:
Welcome to Web4Learners.
Learn JavaScript step by step.
Practice with examples.
This is useful when creating messages, formatted text, or multiline content.
Template Literals vs. String Concatenation
Before template literals, developers often combined strings and variables using the + operator.
const name = "Rahul";
const course = "JavaScript";
const message = "Hello " + name + ", welcome to " + course + ".";
console.log(message);
Output:
Hello Rahul, welcome to JavaScript.
With template literals, the same result can be written more clearly.
const name = "Rahul";
const course = "JavaScript";
const message = `Hello ${name}, welcome to ${course}.`;
console.log(message);
Output:
Hello Rahul, welcome to JavaScript.
Template literals are often easier to read when a string contains multiple variables or expressions.
JavaScript String Methods
JavaScript provides built-in string methods for searching, extracting, replacing, splitting, and transforming text.
Strings are immutable, meaning string methods do not change the original string. Methods generally return a new string or another value.
toUpperCase()
The toUpperCase() method returns a string with its letters converted to uppercase.
const message = "Hello JavaScript";
console.log(message.toUpperCase());
Output:
HELLO JAVASCRIPT
toLowerCase()
The toLowerCase() method returns a string with its letters converted to lowercase.
const message = "HELLO JAVASCRIPT";
console.log(message.toLowerCase());
Output:
hello javascript
These methods are useful for normalizing text before comparisons.
trim()
The trim() method removes whitespace from the beginning and end of a string. It does not remove spaces between words.
const message = " Hello JavaScript ";
console.log(message.trim());
Output:
Hello JavaScript
This is commonly used when processing form inputs.
includes()
The includes() method checks whether a string contains a specified sequence of characters. It returns true or false.
const message = "Learn JavaScript online";
console.log(message.includes("JavaScript"));
console.log(message.includes("Python"));
Output:
true
false
By default, includes() is case-sensitive.
indexOf()
The indexOf() method returns the index of the first occurrence of a specified substring. It returns -1 if the substring is not found.
const message = "Learn JavaScript";
console.log(message.indexOf("JavaScript"));
console.log(message.indexOf("Python"));
Output:
6
-1
The word "JavaScript" begins at index 6 because indexing starts at 0.
slice()
The slice() method extracts part of a string and returns it as a new string.
Syntax:
string.slice(start, end);
The start index is included, but the end index is excluded.
const language = "JavaScript";
console.log(language.slice(0, 4));
console.log(language.slice(4));
Output:
Java
Script
You can also use negative indexes to count from the end of a string.
const language = "JavaScript";
console.log(language.slice(-6));
Output:
Script
substring()
The substring() method extracts characters between two indexes. The ending index is excluded.
const language = "JavaScript";
console.log(language.substring(0, 4));
console.log(language.substring(4, 10));
Output:
Java
Script
Unlike slice(), substring() treats negative arguments as 0 and swaps the arguments when the first index is greater than the second.
replace()
The replace() method returns a new string in which the first matching substring or pattern is replaced.
const message = "I like Java. Java is popular.";
console.log(message.replace("Java", "JavaScript"));
Output:
I like JavaScript. Java is popular.
By default, replacing a plain string changes only the first match. To replace all matches, you can use replaceAll().
const message = "Java is popular. Java is powerful.";
console.log(message.replaceAll("Java", "JavaScript"));
Output:
JavaScript is popular. JavaScript is powerful.
concat()
The concat() method joins strings and returns the combined result.
const firstName = "Rahul";
const lastName = "Kumar";
const fullName = firstName.concat(" ", lastName);
console.log(fullName);
Output:
Rahul Kumar
You can also use template literals or the + operator for string concatenation.
split()
The split() method divides a string into an array of substrings using a specified separator.
const languages = "HTML,CSS,JavaScript";
console.log(languages.split(","));
Output:
["HTML", "CSS", "JavaScript"]
You can use split(" ") to divide a sentence into words.
const message = "Learn JavaScript today";
console.log(message.split(" "));
Output:
["Learn", "JavaScript", "today"]
To learn how to work with the resulting array, explore the JavaScript arrays tutorial.
startsWith()
The startsWith() method checks whether a string begins with a specified substring.
const message = "Welcome to JavaScript";
console.log(message.startsWith("Welcome"));
console.log(message.startsWith("JavaScript"));
Output:
true
false
endsWith()
The endsWith() method checks whether a string ends with a specified substring.
const filename = "report.pdf";
console.log(filename.endsWith(".pdf"));
console.log(filename.endsWith(".jpg"));
Output:
true
false
This can be useful when checking file extensions, although actual file validation may require additional checks.
repeat()
The repeat() method returns a new string containing the original string repeated a specified number of times.
const symbol = "*";
console.log(symbol.repeat(5));
Output:
*****
The repeat count must be a non-negative number within the method’s allowed range.
charAt()
The charAt() method returns the character at a specified index.
const language = "JavaScript";
console.log(language.charAt(0));
console.log(language.charAt(4));
Output:
J
S
This is useful when you need to access one character by its position.
at()
The at() method returns the character at a specified index. It also supports negative indexes, which count backward from the end.
const language = "JavaScript";
console.log(language.at(0));
console.log(language.at(-1));
Output:
J
t
The at() method provides a convenient way to access the last character of a string.
Common String Methods at a Glance
| Method or property | Purpose | Example |
|---|---|---|
length | Gets the number of UTF-16 code units | "Hello".length |
toUpperCase() | Converts letters to uppercase | "hello".toUpperCase() |
toLowerCase() | Converts letters to lowercase | "HELLO".toLowerCase() |
trim() | Removes surrounding whitespace | " hi ".trim() |
includes() | Checks whether text is present | "JavaScript".includes("Script") |
indexOf() | Finds the first matching index | "JavaScript".indexOf("Script") |
slice() | Extracts part of a string | "JavaScript".slice(0, 4) |
substring() | Extracts characters between indexes | "JavaScript".substring(0, 4) |
replace() | Replaces the first matching substring or pattern | "cat".replace("c", "b") |
replaceAll() | Replaces all matching substrings or patterns | "a-a".replaceAll("a", "b") |
split() | Splits a string into an array | "a,b".split(",") |
concat() | Joins strings | "Hello".concat(" World") |
startsWith() | Checks the beginning of a string | "Hello".startsWith("He") |
endsWith() | Checks the end of a string | "report.pdf".endsWith(".pdf") |
repeat() | Repeats a string | "ha".repeat(3) |
charAt() | Gets a character by index | "Hello".charAt(1) |
at() | Gets a character using positive or negative indexing | "Hello".at(-1) |
Are JavaScript Strings Mutable?
No. JavaScript strings are immutable, which means you cannot change individual characters in an existing string.
let language = "JavaScript";
language[0] = "Y";
console.log(language);
Output:
JavaScript
The original string remains unchanged. To create a modified string, assign a new string value.
let language = "JavaScript";
language = "Y" + language.slice(1);
console.log(language);
Output:
YavaScript
Although the variable language can be reassigned because it was declared with let, the original string itself was not modified.
Frequently Asked Questions
What is a string in JavaScript?
A string is a primitive data type used to represent text. You can create a string using single quotes, double quotes, or backticks.
What is string indexing?
String indexing lets you access characters by their positions. JavaScript uses zero-based indexing, so the first character is at index 0.
What does the length property do?
The length property returns the number of UTF-16 code units in a string. For ordinary English text, this generally matches the number of visible characters.
What is the difference between a string and a template literal?
A regular string uses single or double quotes. A template literal uses backticks and supports embedded expressions with ${...} and multiline text.
Do JavaScript string methods change the original string?
No. JavaScript strings are immutable. String methods generally return a new string or another value without modifying the original string.
How do you check whether a string contains specific text?
Use includes(). For example, "JavaScript".includes("Script") returns true.
How do you convert a string into an array?
Use split() with a separator. For example, "HTML,CSS,JavaScript".split(",") returns an array containing three strings.
What to Learn Next
After learning JavaScript strings, continue with JavaScript Numbers and Math Methods to understand numeric values, calculations, rounding, and other mathematical operations in JavaScript.