JavaScript Strings

What Are Strings in JavaScript?

In JavaScript, strings are sequences of characters used to represent and manipulate text. They are one of the most commonly used data types and can include letters, numbers, symbols and spaces. Strings in JavaScript are immutable, meaning their content cannot be changed after creation, though you can create new strings based on transformations of existing ones.

How to Create Strings in JavaScript

There are three ways to define strings in JavaScript:

  1. Using Double Quotes (")
  2. Using Single Quotes (')
  3. Using Backticks (`) for Template Literals

Examples:

let doubleQuoteString = "Hello, World!";
let singleQuoteString = 'Hello, JavaScript!';
let templateLiteralString = `Hello, ${doubleQuoteString}`;

Properties of Strings

Strings come with a useful property:

  • length: Returns the number of characters in a string.

Example:

let message = "JavaScript";
console.log(message.length); // Output: 10

Common String Operations

1. Concatenation

Joining two or more strings using the + operator or concat() method.

Example:

let firstName = "John";
let lastName = "Doe";
let fullName = firstName + " " + lastName; // Using +
console.log(fullName); // Output: John Doe

let fullNameConcat = firstName.concat(" ", lastName); // Using concat()
console.log(fullNameConcat); // Output: John Doe

2. Accessing Characters

Use charAt(index) or bracket notation to access individual characters.

Example:

javascriptCopy codelet word = "JavaScript";
console.log(word.charAt(4)); // Output: S
console.log(word[4]); // Output: S

3. String Comparison

Compare strings using === or relational operators.

Example:

javascriptCopy codelet str1 = "apple";
let str2 = "banana";

console.log(str1 === str2); // Output: false
console.log(str1 < str2); // Output: true (alphabetical order)

JavaScript String Methods

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

1. toUpperCase() and toLowerCase()

Convert strings to uppercase or lowercase.

Example:

let greeting = "Hello, World!";
console.log(greeting.toUpperCase()); // Output: HELLO, WORLD!
console.log(greeting.toLowerCase()); // Output: hello, world!

2. trim()

Removes whitespace from both ends of a string.

Example:

let input = "   Hello!   ";
console.log(input.trim()); // Output: Hello!

3. slice()

Extracts a part of a string and returns it as a new string.

Example:

let sentence = "JavaScript is fun!";
console.log(sentence.slice(0, 10)); // Output: JavaScript

4. replace() and replaceAll()

Replaces parts of a string.

Example:

let text = "I love JavaScript. JavaScript is awesome!";
console.log(text.replace("JavaScript", "Python")); // Replaces the first occurrence
// Output: I love Python. JavaScript is awesome!

console.log(text.replaceAll("JavaScript", "Python")); // Replaces all occurrences
// Output: I love Python. Python is awesome!

5. split()

Splits a string into an array based on a delimiter.

Example:

let csv = "red,blue,green";
let colors = csv.split(",");
console.log(colors); // Output: ["red", "blue", "green"]

6. includes()

Checks if a string contains a specified substring.

Example:

let phrase = "JavaScript is powerful!";
console.log(phrase.includes("powerful")); // Output: true

7. startsWith() and endsWith()

Checks whether a string starts or ends with a specific sequence.

Example:

let statement = "Learn JavaScript!";
console.log(statement.startsWith("Learn")); // Output: true
console.log(statement.endsWith("!")); // Output: true

Template Literals

Template literals are enclosed by backticks ( ` ) and allow embedded expressions.

Features:

  • Multiline strings.
  • Interpolation using ${expression}.

Example:

let name = "John";
let age = 25;

let message = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(message);
// Output: Hello, my name is John and I am 25 years old.

Escaping Characters

Use a backslash (\) to escape special characters.

Example:

let quote = "She said, \"JavaScript is amazing!\"";
console.log(quote);
// Output: She said, "JavaScript is amazing!"

Practical Example: Reversing a String

Code Example:

function reverseString(str) {
return str.split("").reverse().join("");
}

console.log(reverseString("JavaScript"));
// Output: tpircSavaJ

Leave a Comment

BoxofLearn