Strings are a very important data type in JavaScript. They are used to store and work with text. This tutorial will teach you what strings are, how to make them, and how to do useful things with them. You will learn how to combine text and change how it looks.
String
String
In JavaScript, a string is a type of data that holds text. Think of it like a container for words, letters, numbers, or any other characters you want to write. Strings are everywhere in programming. They are used for names, messages, website addresses, and more. Understanding strings helps you work with all kinds of text information in your programs.
What is a String?
A string is a sequence of characters, like letters, numbers, or symbols, enclosed within single quotes, double quotes, or backticks.
Text Data
Strings are used to store any kind of text information, such as names, sentences, or paragraphs.
Quotes Matter
You must put text inside quotes (single, double, or backticks) to make it a string in JavaScript.
Length Property
Strings have a .length property that tells you how many characters are in the text.
Built-in Methods
JavaScript provides many helpful methods to perform actions like changing text to uppercase or finding specific parts.
Creating Your First String
Creating Your First String
To create a string, you simply put your text inside quotation marks. You can use either single quotes (') or double quotes ("). Both work the same way for simple text. JavaScript knows that anything inside these quotes is text data, not a number or a command.
1let userName = "Alex"; // This creates a string with double quotes2let message = 'Hello there!'; // This creates a string with single quotes3let product = `Laptop`; // This uses backticks, also creates a string45console.log(userName); // Shows 'Alex' in the console6console.log(message); // Shows 'Hello there!'7console.log(product); // Shows 'Laptop'
Don't Forget the Quotes!
If you forget to put quotes around your text, JavaScript will think it's a variable name or a command. This will often cause an error because it won't understand what Hello means without quotes. Always use quotes for text data.
Combining Strings (Concatenation)
Combining Strings (Concatenation)
Often, you will need to join two or more strings together. This is called concatenation. You can do this using the plus sign (+) operator. The + sign works differently with strings than it does with numbers. When you use + with strings, it sticks them together side-by-side.
1let firstName = "Jane";2let lastName = "Doe";34// Use '+' to join firstName, a space, and lastName5let fullName = firstName + " " + lastName;67console.log(fullName); // Output: "Jane Doe"89let greeting = "Welcome, " + fullName + "!";10console.log(greeting); // Output: "Welcome, Jane Doe!"
For more complex messages, using many + signs can become hard to read. There is a better way to combine strings with variables, called template literals. Template literals use backticks (`) instead of quotes. Inside template literals, you can put variables directly using ${}.
let item = "Book";let price = 15;let message = "Your " + item + " costs $" + price + ". Thank you!";// Output: "Your Book costs $15. Thank you!"
let item = "Book";let price = 15;let message = `Your ${item} costs $${price}. Thank you!`;// Output: "Your Book costs $15. Thank you!"
Choosing Your String Quotes
Choosing Your String Quotes
JavaScript gives you three ways to define strings: single quotes, double quotes, and backticks. For simple strings, single and double quotes work almost exactly the same. Your choice often comes down to personal preference or what your team agrees on. However, backticks offer special features that are very useful.
let greeting = 'Hello world!';let quote = 'He said, "Hi!"'; // Need to escape double quoteslet message = 'It\'s a beautiful day.'; // Need to escape single quote
let greeting = "Hello world!";let quote = "He said, 'Hi!'"; // Single quotes inside are finelet message = "It's a beautiful day."; // Single quote inside is fine
let greeting = 'Hello world!';let quote = 'He said, "Hi!"'; // Need to escape double quoteslet message = 'It\'s a beautiful day.'; // Need to escape single quote
let greeting = "Hello world!";let quote = "He said, 'Hi!'"; // Single quotes inside are finelet message = "It's a beautiful day."; // Single quote inside is fine
When to Use Backticks (Template Literals)
Use backticks (`) for strings when you need to embed variables or expressions directly into the text, like ${variableName}. They also make it easy to create multi-line strings without special characters. This makes your code much cleaner and easier to read, especially for longer messages.
Working with Strings: Common Actions
Working with Strings: Common Actions
Strings are not just for displaying text. You can also get information about them or change how they look. JavaScript has many built-in tools called methods that let you do cool things with strings. Let's look at some common ones.
Get the Length of a String
Every string has a .length property. This property tells you how many characters are in the string, including spaces and symbols.
1let animal = "Elephant";2let numberOfLetters = animal.length;3console.log(numberOfLetters); // Output: 8
Change Case: toUpperCase() and toLowerCase()
You can easily change all letters in a string to uppercase or lowercase. These are methods, so you need to add () after their names.
1let city = "london";2let bigCity = city.toUpperCase(); // Changes all letters to uppercase3console.log(bigCity); // Output: "LONDON"45let shout = "HEY THERE!";6let whisper = shout.toLowerCase(); // Changes all letters to lowercase7console.log(whisper); // Output: "hey there!"
Find a Part of a String: indexOf()
The .indexOf() method helps you find where a specific character or word starts within a string. It gives you a number (its position). If it can't find it, it returns -1.
1let sentence = "Hello, world!";2let commaPosition = sentence.indexOf(","); // Find the position of ','3console.log(commaPosition); // Output: 5 (H is 0, e is 1, etc.)45let wordPosition = sentence.indexOf("world"); // Find the position of 'world'6console.log(wordPosition); // Output: 778let notFound = sentence.indexOf("code"); // 'code' is not in the string9console.log(notFound); // Output: -1
Strings are Immutable!
This is very important: once a string is created, you cannot change its individual characters. When you use methods like toUpperCase(), they don't change the original string. Instead, they create a brand new string with the changes. You must save this new string in a variable if you want to use it.
String Properties and Methods Reference
String Properties and Methods Reference
Here is a quick overview of some common properties and methods you will use when working with strings in JavaScript. Remember, methods usually need () after their name, while properties do not.
| Property/Method | Description | Example | Returns |
|---|---|---|---|
| `length` | Returns the number of characters in the string. | `'apple'.length` | A number |
| `toUpperCase()` | Converts all characters in the string to uppercase. | `'hello'.toUpperCase()` | A new string |
| `toLowerCase()` | Converts all characters in the string to lowercase. | `'WORLD'.toLowerCase()` | A new string |
| `indexOf(searchString)` | Returns the first position of `searchString`. Returns `-1` if not found. | `'banana'.indexOf('an')` | A number (index) |
| `includes(searchString)` | Checks if the string contains `searchString`. Returns `true` or `false`. | `'apple'.includes('pp')` | A boolean (`true`/`false`) |
| `substring(start, end)` | Extracts characters from `start` up to (but not including) `end`. | `'orange'.substring(1, 4)` | A new string |
| `replace(old, new)` | Replaces the first occurrence of `old` with `new`. | `'dog'.replace('d', 'f')` | A new string |
Test Your Knowledge
Test Your Knowledge
Which of the following is NOT a valid way to create a string in JavaScript?
What will be the value of result after this code runs?
let a = "Code";
let b = "Master";
let result = a + b;
If let text = "Orange";, what will text.toUpperCase() return?
Which statement best describes string immutability in JavaScript?
Quick Reference
Quick Reference
- 1Definition — A string is a sequence of characters used to represent text data.
- 2Creation — Strings are created by enclosing text in single quotes (
'text'), double quotes ("text"), or backticks (`text`). - 3Concatenation — Use the
+operator to join two or more strings together, like"Hello" + "World". - 4Template Literals — Use backticks (
`) for easily embedding variables with${variable}and for multi-line strings. - 5Length Property — The
.lengthproperty tells you the number of characters in a string (e.g.,"abc".lengthis3). - 6toUpperCase() — Converts all letters in a string to uppercase (e.g.,
"hello".toUpperCase()becomes"HELLO"). - 7toLowerCase() — Converts all letters in a string to lowercase (e.g.,
"WORLD".toLowerCase()becomes"world"). - 8indexOf() — Finds the starting position (index) of a specific substring within a string; returns
-1if not found. - 9Immutable — Strings cannot be changed after they are created; methods like
replace()return a new string. - 10Escape Characters — Use a backslash (
\) to include special characters inside a string, like\'sfor an apostrophe in a single-quoted string.
Numbers
Learn about the Number data type for working with numerical values and calculations.
Booleans
Explore Boolean values (true or false) used for making decisions in your code.
Variables
Understand how to declare and use variables to store and manage data in your programs.
Operators
Discover different operators (arithmetic, comparison) for performing actions on your data.
Great Job!
You've learned all about strings in JavaScript! You now know how to create text, combine it, and use powerful methods to work with it. Strings are fundamental, and mastering them is a big step in your coding journey. Keep practicing!
Try it in the Javascript Compiler
Run and experiment with Javascript code right in your browser — no setup needed.