JavaScript Strings

Strings in JavaScript are one of the most commonly used data types. A string is a sequence of characters used to represent text. Whether you’re working with names, messages, or HTML content, strings are essential.

This tutorial covers how to create, manipulate, and work with strings in JavaScript.


1. What Is a String?

In JavaScript, a string is a text value enclosed in single quotes ' ', double quotes " ", or backticks ` `.

javascriptCopyEditlet name1 = 'Alice';
let name2 = "Bob";
let greeting = `Hello, ${name1}!`; // Template literal

All three are valid, but backticks allow for template literals, which support string interpolation and multiline strings.


2. String Length

The .length property returns the number of characters in a string:

javascriptCopyEditlet text = "JavaScript";
console.log(text.length); // 10

3. Accessing Characters

You can access characters in a string using bracket notation:

javascriptCopyEditlet str = "Hello";
console.log(str[0]); // H
console.log(str.charAt(1)); // e

4. String Methods

JavaScript provides many built-in methods for working with strings. Here are the most useful ones:

toUpperCase() / toLowerCase()

Converts the string to uppercase or lowercase.

javascriptCopyEditlet city = "london";
console.log(city.toUpperCase()); // LONDON
console.log(city.toLowerCase()); // london

trim()

Removes whitespace from both ends of the string.

javascriptCopyEditlet messy = "  hello world  ";
console.log(messy.trim()); // "hello world"

slice(start, end)

Extracts a part of a string.

javascriptCopyEditlet word = "JavaScript";
console.log(word.slice(0, 4)); // "Java"

substring(start, end)

Similar to slice(), but doesn’t accept negative indexes.

javascriptCopyEditconsole.log(word.substring(4, 10)); // "Script"

replace()

Replaces part of a string.

javascriptCopyEditlet msg = "I like apples";
console.log(msg.replace("apples", "bananas")); // I like bananas

To replace all occurrences, use a regular expression with the g flag:

javascriptCopyEditlet text = "apples are apples";
console.log(text.replace(/apples/g, "oranges")); // oranges are oranges

includes()

Checks if a string contains another string.

javascriptCopyEditlet email = "test@example.com";
console.log(email.includes("@")); // true

startsWith() / endsWith()

Checks how a string begins or ends.

javascriptCopyEditlet file = "report.pdf";
console.log(file.endsWith(".pdf")); // true

split()

Converts a string into an array.

javascriptCopyEditlet fruits = "apple,banana,orange";
console.log(fruits.split(",")); // ["apple", "banana", "orange"]

concat()

Joins two or more strings.

javascriptCopyEditlet first = "Hello";
let second = "World";
console.log(first.concat(" ", second)); // "Hello World"

5. Template Literals (Backticks “)

Template literals allow you to embed variables and expressions directly inside strings using ${}.

javascriptCopyEditlet name = "Sarah";
let age = 30;
let intro = `My name is ${name} and I am ${age} years old.`;
console.log(intro);

They also support multiline strings:

javascriptCopyEditlet multiline = `This is line 1
This is line 2`;
console.log(multiline);

6. Escape Characters

Use backslashes to include special characters:

javascriptCopyEditlet quote = 'She said, "Hello!"';
let lineBreak = "First line\nSecond line";
let backslash = "This is a backslash: \\";

7. Comparing Strings

You can use comparison operators:

javascriptCopyEditconsole.log("apple" === "apple"); // true
console.log("a" < "b"); // true (alphabetical)

JavaScript compares strings based on Unicode values.


8. String Immutability

Strings in JavaScript are immutable, meaning you cannot change characters directly:

javascriptCopyEditlet str = "Hello";
str[0] = "Y"; // ❌ Doesn't work

Instead, create a new string:

javascriptCopyEditstr = "Y" + str.slice(1); // "Yello"

Conclusion

JavaScript strings are powerful and versatile. Here’s a quick recap of what you learned:

ConceptExample
Length"hello".length5
Access character"hello"[0]"h"
Methodsslice, replace, split
Template literals`Hello ${name}`
ImmutabilityStrings can’t be changed in place

Leave a Reply

Your email address will not be published. Required fields are marked *