Skip to content
GitHub

Working with Strings

Switch to Zen Mode
Examples: String Creation
const single = 'Hello';
const double = "World";
const template = `Hello, ${double}!`; // Template literal with interpolation
console.log(template); // Output: Hello, World!
javascript

A string in JavaScript can be created in several ways:

  1. Literal Notation:

    const str1 = "JavaScript";
    const str2 = 'is fun';
    javascript
  2. String Constructor (less common):

    const str3 = new String("Hello"); // Creates a String object (not a primitive)
    console.log(typeof str3); // Output: object
    javascript
    • Note: Prefer literals over the constructor for simplicity and performance.
  3. Template Literals (ES6+):

    const name = "Alice";
    const greeting = `Hi, ${name}!`; // Supports expressions
    console.log(greeting); // Output: Hi, Alice!
    javascript

  • length: Returns the number of characters in the string.
    const str = "Hello";
    console.log(str.length); // Output: 5
    javascript

const name = "Bob";
const message = `
Hello, ${name}!
How are you today?
`;
console.log(message);
// Output:
// Hello, Bob!
// How are you today?
javascript

You can access object properties directly within ${} for concise and readable string construction:

const user = {
firstName: "Michel",
age: 25,
address: {
city: "Montreal",
country: "Canada"
}
};
const greeting = `Welcome, ${user.firstName}! You are ${user.age} years old and live in ${user.address.city}, ${user.address.country}.`;
console.log(greeting);
// Output: Welcome, Michel! You are 25 years old and live in Montreal, Canada.
javascript

You can also include expressions involving object properties:

const product = {
name: "Laptop",
price: 999.99,
discount: 0.1 // 10% discount
};
const offer = `${product.name} on sale: $${(product.price * (1 - product.discount)).toFixed(2)} after a ${product.discount * 100}% discount!`;
console.log(offer);
// Output: Laptop on sale: $899.99 after a 10% discount!
javascript


Use \ to escape special characters:

  • \" or \': Include quotes in a string.
  • \n: Newline.
  • \t: Tab.
  • \\: Backslash.
const str = "She said, \"Hi!\"\nNew line.";
console.log(str);
// Output:
// She said, "Hi!"
// New line.
javascript

  • charAt(index): Returns the character at the specified index (0-based).
    const str = "Hello";
    console.log(str.charAt(1)); // Output: e
    javascript
  • [index]: Array-like access (shorter syntax).
    console.log(str[1]); // Output: e
    javascript
  • charCodeAt(index): Returns the UTF-16 code of the character at the index.
    console.log(str.charCodeAt(0)); // Output: 72 (ASCII/UTF-16 code for 'H')
    javascript

  • indexOf(substring, [start]): Returns the first index of the substring, or -1 if not found.
    const str = "Hello World";
    console.log(str.indexOf("World")); // Output: 6
    console.log(str.indexOf("z")); // Output: -1
    javascript
  • lastIndexOf(substring, [start]): Returns the last index of the substring.
    console.log(str.lastIndexOf("l")); // Output: 9
    javascript
  • includes(substring, [start]): Returns true if the substring exists.
    console.log(str.includes("Hello")); // Output: true
    javascript
  • startsWith(substring, [start]): Checks if the string starts with the substring.
    console.log(str.startsWith("He")); // Output: true
    javascript
  • endsWith(substring, [length]): Checks if the string ends with the substring.
    console.log(str.endsWith("ld")); // Output: true
    javascript

  • toLowerCase(): Converts the string to lowercase.
    const str = "HELLO";
    console.log(str.toLowerCase()); // Output: hello
    javascript
  • toUpperCase(): Converts the string to uppercase.
    console.log(str.toUpperCase()); // Output: HELLO
    javascript
  • trim(): Removes whitespace from both ends.
    const str = " Hello ";
    console.log(str.trim()); // Output: Hello
    javascript
  • trimStart() / trimEnd(): Removes whitespace from the start or end.
    console.log(str.trimStart()); // Output: "Hello "
    javascript
  • replace(search, replacement): Replaces the first match with a new value.
    const str = "Hello World";
    console.log(str.replace("World", "JavaScript")); // Output: Hello JavaScript
    javascript
  • replaceAll(search, replacement) (ES2021+): Replaces all matches.
    const str = "Hello Hello";
    console.log(str.replaceAll("Hello", "Hi")); // Output: Hi Hi
    javascript
  • slice(start, [end]): Extracts a portion of the string.
    const str = "Hello World";
    console.log(str.slice(0, 5)); // Output: Hello
    javascript
  • substring(start, [end]): Similar to slice, but doesn’t accept negative indices.
    console.log(str.substring(6)); // Output: World
    javascript
  • split(separator, [limit]): Splits the string into an array based on a separator.
    const str = "apple,banana,orange";
    console.log(str.split(",")); // Output: ["apple", "banana", "orange"]
    javascript

  • concat(...strings): Combines strings.
    const str1 = "Hello";
    const str2 = "World";
    console.log(str1.concat(" ", str2)); // Output: Hello World
    javascript
  • Using + or += (more common):
    console.log(str1 + " " + str2); // Output: Hello World
    javascript
  • padStart(targetLength, padString): Pads the start of the string.
    const str = "5";
    console.log(str.padStart(3, "0")); // Output: 005
    javascript
  • padEnd(targetLength, padString): Pads the end of the string.
    console.log(str.padEnd(3, "0")); // Output: 500
    javascript
  • repeat(count): Repeats the string a specified number of times.
    const str = "Hi ";
    console.log(str.repeat(3)); // Output: Hi Hi Hi
    javascript

Strings in JavaScript are immutable—methods don’t modify the original string but return a new one:

const str = "Hello";
const newStr = str.toUpperCase();
console.log(str); // Output: Hello (unchanged)
console.log(newStr); // Output: HELLO
javascript

  • Use === for exact comparison (case-sensitive):
    console.log("hello" === "Hello"); // Output: false
    javascript
  • Use localeCompare() for locale-aware comparison:
    console.log("apple".localeCompare("banana")); // Output: -1 (apple comes before banana)
    javascript

  1. Use Template Literals: Prefer backticks for readability and interpolation.
  2. Avoid Excessive Concatenation: Use arrays and join() for performance with large strings:
    const parts = ["Hello", "World"];
    console.log(parts.join(" ")); // Output: Hello World
    javascript
  3. Handle Edge Cases: Check for empty strings or undefined:
    const str = "";
    console.log(str.length || "Empty"); // Output: Empty
    javascript
  4. Case Sensitivity: Normalize case with toLowerCase() or toUpperCase() when comparing.
  5. Use Modern Methods: Prefer includes() over indexOf() !== -1 for readability.

  • Parsing User Input: Split and trim strings from forms.
  • Formatting Output: Use template literals for dynamic messages.
  • Data Serialization: Convert objects to JSON strings with JSON.stringify().

  • Type Errors: Ensure the value is a string before calling methods (typeof str === "string").
  • Out-of-Bounds: Accessing an invalid index returns undefined, not an error.
    console.log("Hello"[10]); // Output: undefined
    javascript
  • Encoding: Use encodeURIComponent() for URLs or special characters.

A practical example demonstrating how to use object properties in template literals to generate a formatted message:

// Define an object with nested properties
const employee = {
id: 123,
name: "John Doe",
role: "Developer",
department: {
name: "Engineering",
location: "Building A"
},
salary: 75000
};
// Create a template literal using object properties
const employeeSummary = `
Employee ID: ${employee.id}
Name: ${employee.name}
Role: ${employee.role}
Department: ${employee.department.name}
Location: ${employee.department.location}
Annual Salary: $${employee.salary.toLocaleString("en-US")}
`;
// Output the result
console.log(employeeSummary);
// Output:
// Employee ID: 123
// Name: John Doe
// Role: Developer
// Department: Engineering
// Location: Building A
// Annual Salary: $75,000
javascript