JavaScript Strings

1. What is a String?

A string is a sequence of characters used to represent text. It is one of the primitive data types in JavaScript. Strings are immutable, which means once a string is created, it cannot be changed. String methods don't change the original string; they return a new one.

2. Creating Strings

Strings can be created using single quotes (''), double quotes (""), or backticks (``).

// Using double and single quotes
let singleQuote = 'Hello';
let doubleQuote = "World";

// Template Literals (ES6) with backticks
let name = "Ragini";
let greeting = `Hello, ${name}!`; // Allows embedding variables

document.write(greeting);
        
Output will appear here...

3. Common String Methods

JavaScript provides a rich set of methods to manipulate strings.

length (Property)

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

let text = "Hello World";
document.write(text.length); // 11
        
Output will appear here...

slice(start, end)

Extracts a part of a string and returns it as a new string. The end index is not included. Negative indices can be used to count from the end.

let text = "JavaScript";
document.write(text.slice(0, 4));  // "Java"
document.write(text.slice(4));     // "Script"
document.write(text.slice(-3));    // "ipt"
        
Output will appear here...

toUpperCase() and toLowerCase()

These methods convert a string to uppercase or lowercase, respectively.

let msg = "Hello World";
document.write(msg.toUpperCase()); // "HELLO WORLD"
document.write(msg.toLowerCase()); // "hello world"
        
Output will appear here...

replace(searchValue, newValue)

Replaces the first occurrence of a specified value with another value. To replace all occurrences, use replaceAll() or a regular expression with the global flag.

let text = "I love Java, because Java is great.";
document.write(text.replace("Java", "JavaScript")); // "I love JavaScript, because Java is great."
document.write(text.replaceAll("Java", "JavaScript")); // "I love JavaScript, because JavaScript is great."
        
Output will appear here...

trim()

Removes whitespace from both ends of a string. trimStart() and trimEnd() remove whitespace from the beginning or end only.

let text = "   Hello World   ";
document.write(text.trim()); // "Hello World"
        
Output will appear here...

split(separator)

Splits a string into an array of substrings based on a specified separator.

let text = "HTML,CSS,JS";
let skills = text.split(",");
document.write(skills); // ["HTML", "CSS", "JS"]
        
Output will appear here...

includes(searchValue)

Checks if a string contains a specified value. It returns true or false and is case-sensitive.

let text = "JavaScript is awesome";
document.write(text.includes("Script")); // true
document.write(text.includes("script")); // false
        
Output will appear here...

4. Comparison: Array vs. String

Feature Array String
Type Object (Non-Primitive) Primitive
Mutability Mutable (can be changed) Immutable (cannot be changed)
Stores Elements of any type A sequence of characters
Example [1, "hi", true] "Hello World"
Best Practice: Use Template Literals (``) for creating strings that involve variables or multiple lines. Remember that strings are immutable; methods always return new strings.

Practice Questions

Test your understanding of JavaScript Strings.

Easy

Q1: Find the length of a string.

  • Declare a string variable with the value "Hello".
  • Use the appropriate property to find its length.
  • Log the output to the console.
Easy

Q2: Convert a string to uppercase.

  • Declare a string: let str = "javascript";
  • Use the correct string method to convert all characters to uppercase.
  • Log the result to the console.
Medium

Q3: Extract a portion of a string.

  • Declare a string: let text = "Hello World";
  • Use the slice() method to extract the word "World".
  • Log the extracted word to the console.
Medium

Q4: Replace a specific word in a sentence.

  • Declare a string: let sentence = "I like apples.";
  • Use the replace() method to change "apples" to "oranges".
  • Log the new sentence to the console.
Hard

Q5: Split a string into an array.

  • Declare a string: let data = "one,two,three";
  • Use the split() method with a comma "," as the separator.
  • Log the resulting array to the console.

Answer

Code: