#atom
ID: CS-009
Date: [Insert Date]

Content:
In JavaScript, a string is a primitive data type used to represent textual data. Strings are immutable, meaning once created, they cannot be changed. However, JavaScript provides many methods for manipulating strings and creating new ones.

Ways to Create Strings in JavaScript:

  1. Using Single Quotes:

    const str1 = 'Hello, World!';
    
  2. Using Double Quotes:

    const str2 = "Hello, World!";
    
  3. Using Backticks (Template Literals):

    const str3 = `Hello, World!`;
    
  4. Using the String Constructor:

    const str4 = String('Hello, World!');
    
  5. Creating Multiline Strings:

    • Using backticks (template literals):
      const multilineStr = `
      This is a
      multiline
      string.
      `;
      
    • Using concatenation:
      const multilineStr = 'This is a\n' +
                           'multiline\n' +
                           'string.';
      
  6. Creating Strings from Variables (Interpolation):

    const name = 'Alice';
    const greeting = `Hello, ${name}!`; // "Hello, Alice!"
    

Common String Methods in JavaScript:

  1. length: Get the length of a string.

    const str = 'Hello';
    console.log(str.length); // 5
    
  2. toUpperCase() and toLowerCase(): Convert case.

    const str = 'Hello';
    console.log(str.toUpperCase()); // "HELLO"
    console.log(str.toLowerCase()); // "hello"
    
  3. substring() and slice(): Extract substrings.

    const str = 'Hello, World!';
    console.log(str.substring(0, 5)); // "Hello"
    console.log(str.slice(-6)); // "World!"
    
  4. indexOf() and includes(): Search for substrings.

    const str = 'Hello, World!';
    console.log(str.indexOf('World')); // 7
    console.log(str.includes('Hello')); // true
    
  5. replace(): Replace parts of a string.

    const str = 'Hello, World!';
    console.log(str.replace('World', 'Alice')); // "Hello, Alice!"
    
  6. trim(): Remove whitespace from the beginning and end.

    const str = '   Hello, World!   ';
    console.log(str.trim()); // "Hello, World!"
    

Connections:


Connections:


Sources: