In JavaScript, we often need to work with text—usernames, messages, email addresses, product names, sentences, and much more.
For example:
let name = "John";The value "John" is a string.
Strings are one of the most commonly used data types in JavaScript, so let's understand how they work.
What is a String?
A string is a sequence of characters used to represent text.
For example:
let name = "John";
let city = "Delhi";
let message = "Welcome to JavaScript!";All three values are strings.
Creating Strings
JavaScript provides three common ways to create strings.
Double Quotes
let name = "John";Single Quotes
let name = 'John';Backticks
let name = `John`;All three create strings.
Backticks are called template literals, and they provide some extra features that we'll see shortly.
String Length
The .length property tells us how many characters a string contains.
let message = "Hello";
console.log(message.length);Output:
5Spaces are also counted as characters.
let message = "Hello World";
console.log(message.length);Output:
11Accessing Characters
Just like arrays, strings use zero-based indexing.
let word = "Hello";
console.log(word[0]);
console.log(word[1]);
console.log(word[4]);Output:
H
e
oThe indexes look like this:
Index | Character |
|---|---|
| H |
| e |
| l |
| l |
| o |
We can also use at():
console.log(word.at(-1));Output:
oThis is useful when accessing characters from the end of a string.
Strings Are Immutable
Strings in JavaScript are immutable, which means we cannot directly change an individual character.
For example:
let word = "Hello";
word[0] = "Y";
console.log(word);The string remains:
HelloInstead, we create a new string:
let word = "Hello";
word = "Y" + word.slice(1);
console.log(word);Output:
YelloThis is different from arrays, which can have individual elements changed.
Combining Strings
We can combine strings using the + operator.
let firstName = "John";
let lastName = "Smith";
let fullName = firstName + " " + lastName;
console.log(fullName);Output:
John SmithThis is called string concatenation.
Template Literals
For combining text with variables, template literals are often much cleaner.
They use backticks:
let name = "John";
let age = 21;
console.log(`My name is ${name} and I am ${age} years old.`);Output:
My name is John and I am 21 years old.The ${} syntax allows us to insert variables or expressions directly inside the string.
For example:
let price = 100;
let quantity = 3;
console.log(`Total price: ${price * quantity}`);Output:
Total price: 300Template literals can also span multiple lines:
let message = `Hello John,
Welcome to our website!`;
console.log(message);Common String Methods
JavaScript provides many built-in methods for working with strings.
Some important ones are:
Method | Purpose |
|---|---|
| Converts to uppercase |
| Converts to lowercase |
| Removes spaces from both ends |
| Checks whether text exists |
| Checks the beginning |
| Checks the ending |
| Finds the position of text |
| Extracts part of a string |
| Extracts part of a string |
| Replaces text |
| Converts a string into an array |
Let's look at some of the most useful ones.
toUpperCase() and toLowerCase()
These methods change the letter case.
let message = "Hello World";
console.log(message.toUpperCase());
console.log(message.toLowerCase());Output:
HELLO WORLD
hello worldThis is useful when comparing text where letter case shouldn't matter.
trim()
trim() removes whitespace from the beginning and end of a string.
let name = " John ";
console.log(name.trim());Output:
JohnThis is especially useful when processing user input from forms.
includes()
includes() checks whether a string contains a specific piece of text.
let message = "Welcome to JavaScript";
console.log(message.includes("JavaScript"));Output:
trueIf the text doesn't exist:
console.log(message.includes("Python"));Output:
falsestartsWith() and endsWith()
These methods check whether a string starts or ends with specific text.
let fileName = "photo.jpg";
console.log(fileName.startsWith("photo"));
console.log(fileName.endsWith(".jpg"));Output:
true
trueThese can be useful when checking filenames, URLs, or other text patterns.
indexOf()
indexOf() returns the position of the first occurrence of some text.
let message = "Hello World";
console.log(message.indexOf("World"));Output:
6Remember that indexing starts from 0.
If the text isn't found, it returns -1.
console.log(message.indexOf("JavaScript"));Output:
-1slice()
slice() extracts part of a string and returns a new string.
let message = "Hello World";
console.log(message.slice(0, 5));Output:
HelloThe ending index is not included.
We can also use negative indexes:
console.log(message.slice(-5));Output:
Worldreplace()
The replace() method replaces part of a string.
let message = "Hello John";
let result = message.replace("John", "Alex");
console.log(result);Output:
Hello AlexThe original string isn't changed because strings are immutable.
split()
split() breaks a string into an array.
For example:
let fruits = "Apple,Banana,Mango";
let result = fruits.split(",");
console.log(result);Output:
["Apple", "Banana", "Mango"]This is very useful when converting text into a list of values.
For example:
let sentence = "Hello World";
console.log(sentence.split(" "));Output:
["Hello", "World"]Comparing Strings
We can compare strings using comparison operators.
let a = "apple";
let b = "apple";
console.log(a === b);Output:
trueString comparison is case-sensitive:
console.log("hello" === "Hello");Output:
falseIf you want a case-insensitive comparison, you can normalize both strings:
let input = "HELLO";
console.log(input.toLowerCase() === "hello");Output:
trueA Practical Example
Let's say we're processing a username entered by a user.
let username = " JOHN ";
username = username.trim().toLowerCase();
console.log(username);Output:
johnHere, we:
Used
trim()to remove unnecessary spaces.Used
toLowerCase()to convert the text to lowercase.
This kind of string processing is very common when handling user input.
Conclusion
Strings are used whenever our JavaScript program needs to work with text.
Some important things to remember:
Strings can be created using
' '," ", or backticks.String indexes start from
0.Strings are immutable.
.lengthgives the number of characters.+can combine strings.Template literals make it easy to insert variables into text.
Methods such as
trim(),includes(),slice(),replace(), andsplit()make string processing much easier.
Once you become comfortable with strings and their methods, you'll be able to handle everything from usernames and messages to form input and API data much more easily.