Logo
HTMLCSSJavaScriptReactjsnewContactUpdates

Get started today

HTMLCSSJavaScriptReactjsnewContactUpdates

Tools

Resume BuilderQR GeneratorVS Code Editor

Connect

GitHubWhatsApp Channel
rest and spread
prototype

JavaScript String Methods & Operations - Complete Guide

By Saket Bhatnagar•June 15, 2025•Beginner to Intermediate

Table of Contents

  1. What is a string?
  2. Types of String
  3. String Methods
  4. String Practice Questions
  5. Special Characters

What is a string?

  1. 1A string is a sequence of characters enclosed in single quotes, double quotes or backticks.
  2. 2It is a primitive data type in JavaScript.
  3. 3Strings are immutable - once created, their characters cannot be changed.
  4. 4The internal format for strings is always UTF-16, regardless of the page encoding.
  5. 5String Indexing
    • Each character in a string has a position (index) starting from 0
    • The last character is at position string.length - 1
    • Negative indices count from the end of the string
    • 1let str = "Hello";
      2// Indices: 01234
      3
      4// Access characters using index
      5console.log(str[0]); // "H"
      6console.log(str[4]); // "o"
      7console.log(str[-1]); // undefined (use at() for negative indices)
      8console.log(str.at(-1)); // "o" (last character)
  6. 6String Access Methods
    • Square brackets []: Zero-based index access (returns undefined if out of range)
    • charAt(): Returns character at index (returns empty string if out of range)
    • at(): Supports both positive and negative indices
    • 1let str = "JavaScript";
      2
      3// Different ways to access characters
      4console.log(str[0]); // "J"
      5console.log(str.charAt(0)); // "J"
      6console.log(str.at(0)); // "J"
      7
      8// Out of range behavior
      9console.log(str[20]); // undefined
      10console.log(str.charAt(20)); // "" (empty string)
      11console.log(str.at(-1)); // "t" (last character)
      12console.log(str.at(-2)); // "p" (second to last)
  7. 7String Characteristics
    • Immutability: Individual characters cannot be changed after creation
    • Case Sensitivity: String comparisons and methods are case-sensitive by default
    • Unicode Support: Can contain any Unicode characters including emojis
    • 1let str = "Hello";
      2
      3// Immutability
      4str[0] = "h"; // No effect
      5console.log(str); // Still "Hello"
      6
      7// Case sensitivity
      8console.log("Hello" === "hello"); // false
      9
      10// Unicode support
      11let text = "Hello 👋 World 🌍";
      12console.log(text.length); // Length includes emoji characters
      13console.log(text[6]); // "👋" (emoji is a single character)

Types of String

  1. 1There are three types of string in JavaScript:
    1let single = 'single-quoted';
    2let double = "double-quoted";
    3let backticks = `backticks`;
  2. 2Single and double quotes are essentially the same.
  3. 3Backticks allow:
    • Multiline strings
    • String interpolation using ${expression} .
  4. 4Example of template literals:
    1let name = "John";
    2let greeting = \`Hello, ${name}!\`; // Hello, John!
    3
    4let multiline = `
    5 Line 1
    6 Line 2
    7 Line 3
    8`;

String Methods

  1. 1length
    • Used to: Get the number of characters in a string
    • Syntax: str.length
    • Returns: number - the length of the string
    • 1let str = "Hello";
      2console.log(str.length); // 5
      3
      4let empty = "";
      5console.log(empty.length); // 0
  2. 2at(index)
    • Used to: Access a character at a specific position in the string
    • Syntax: str.at(index)
    • Returns: string - single character at the index, or undefined if out of range
    • 1let str = "Hello";
      2console.log(str.at(0)); // H
      3console.log(str.at(-1)); // o (last character)
      4console.log(str.at(-2)); // l (second to last)
  3. 3indexOf(searchString, position)
    • Used to: Find the first occurrence of a substring in a string
    • Syntax: str.indexOf(searchString, [position])
    • Returns: number - index of first match, or -1 if not found
    • 1let str = "Hello World";
      2console.log(str.indexOf("World")); // 6
      3console.log(str.indexOf("world")); // -1 (case sensitive)
      4console.log(str.indexOf("o", 5)); // 7 (starts search from index 5)
  4. 4slice(start, end)
    • Used to: Extract a portion of a string between two indices
    • Syntax: str.slice(startIndex, [endIndex])
    • Returns: string - extracted substring from start to end (not including end)
    • 1let str = "Hello World";
      2console.log(str.slice(0, 5)); // "Hello"
      3console.log(str.slice(6)); // "World"
      4console.log(str.slice(-5)); // "World"
      5console.log(str.slice(-6, -1)); // "Worl"
  5. 5replace(searchValue, replaceValue)
    • Used to: Replace the first occurrence of a substring in a string
    • Syntax: str.replace(searchValue, replaceValue)
    • Returns: string - new string with the first match replaced
    • 1let str = "Hello World";
      2console.log(str.replace("World", "JavaScript")); // "Hello JavaScript"
      3console.log(str.replace("o", "0")); // "Hell0 World"
  6. 6replaceAll(searchValue, replaceValue)
    • Used to: Replace all occurrences of a substring in a string
    • Syntax: str.replaceAll(searchValue, replaceValue)
    • Returns: string - new string with all matches replaced
    • 1let str = "ha ha ha";
      2console.log(str.replaceAll("ha", "he")); // "he he he"
      3console.log(str.replaceAll("a", "o")); // "ho ho ho"
  7. 7charAt(index)
    • Used to: Get the character at a specific position in the string
    • Syntax: str.charAt(index)
    • Returns: string - single character at the index, or empty string if out of range
    • 1let str = "Hello";
      2console.log(str.charAt(0)); // "H"
      3console.log(str.charAt(4)); // "o"
      4console.log(str.charAt(10)); // "" (empty string)
  8. 8charCodeAt(index)
    • Used to: Get the Unicode value of a character at a specific position
    • Syntax: str.charCodeAt(index)
    • Returns: number - Unicode value of character, or NaN if index is out of range
    • 1let str = "Hello";
      2console.log(str.charCodeAt(0)); // 72 (Unicode for 'H')
      3console.log(str.charCodeAt(1)); // 101 (Unicode for 'e')
      4console.log("ABC".charCodeAt(0)); // 65 (Unicode for 'A')
  9. 9lastIndexOf(searchString, position)
    • Returns the last occurrence of searchString
    • Optional position parameter specifies where to start searching from (backwards)
    • 1let str = "Hello World, Hello JavaScript";
      2console.log(str.lastIndexOf("Hello")); // 13
      3console.log(str.lastIndexOf("Hello", 12)); // 0
      4console.log(str.lastIndexOf("Python")); // -1 (not found)
  10. 10includes(searchString, position)
    • Checks if string contains searchString
    • Returns true or false
    • 1let str = "Hello World";
      2console.log(str.includes("World")); // true
      3console.log(str.includes("world")); // false (case sensitive)
      4console.log(str.includes("Hello", 1)); // false (starts search from index 1)
  11. 11startsWith(searchString, position)
    • Checks if string starts with searchString
    • Optional position parameter specifies start position for search
    • 1let str = "Hello World";
      2console.log(str.startsWith("Hello")); // true
      3console.log(str.startsWith("World")); // false
      4console.log(str.startsWith("World", 6)); // true (starts check from index 6)
  12. 12endsWith(searchString, length)
    • Checks if string ends with searchString
    • Optional length parameter limits the search length
    • 1let str = "Hello World";
      2console.log(str.endsWith("World")); // true
      3console.log(str.endsWith("Hello")); // false
      4console.log(str.endsWith("Hello", 5)); // true (checks only first 5 characters)
  13. 13toUpperCase() / toLowerCase()
    • Converts string to upper/lower case
    • Returns new string, original remains unchanged
    • 1let str = "Hello World";
      2console.log(str.toUpperCase()); // HELLO WORLD
      3console.log(str.toLowerCase()); // hello world
      4console.log("JavaScript".toLowerCase()); // javascript
  14. 14trim() / trimStart() / trimEnd()
    • trim() removes whitespace from both ends
    • trimStart() removes whitespace from start
    • trimEnd() removes whitespace from end
    • 1let str = " Hello World ";
      2console.log(str.trim()); // "Hello World"
      3console.log(str.trimStart()); // "Hello World "
      4console.log(str.trimEnd()); // " Hello World"
  15. 15concat(str1, str2, ...)
    • Joins two or more strings
    • Returns new string, originals remain unchanged
    • 1let str1 = "Hello";
      2let str2 = "World";
      3console.log(str1.concat(" ", str2)); // "Hello World"
      4console.log("".concat(1, 2, 3)); // "123"
      5console.log(str1.concat(", ", str2, "!")); // "Hello, World!"
  16. 16substring(start, end)
    • Extracts characters between start and end (end not included)
    • Negative values are treated as 0
    • 1let str = "Hello World";
      2console.log(str.substring(0, 5)); // "Hello"
      3console.log(str.substring(6)); // "World"
      4console.log(str.substring(6, 3)); // "llo" (swaps if start > end)
      5console.log(str.substring(-3)); // "Hello World" (negative becomes 0)
  17. 17split(separator)
    • Used to: Convert a string into an array by splitting at specified separator
    • Syntax: str.split([separator[, limit]])
    • Returns: array - substrings created by splitting the string at separator
    • 1// Split string into words
      2let str = "Hello World JavaScript";
      3console.log(str.split(" ")); // ["Hello", "World", "JavaScript"]
      4
      5// Split with limit
      6console.log(str.split(" ", 2)); // ["Hello", "World"]
      7
      8// Split into characters
      9let text = "Hello";
      10console.log(text.split("")); // ["H", "e", "l", "l", "o"]
      11
      12// Split CSV data
      13let data = "John,Doe,25,Developer";
      14console.log(data.split(",")); // ["John", "Doe", "25", "Developer"]
  18. 18join(separator)
    • Used to: Create a string by concatenating all elements of an array
    • Syntax: array.join([separator])
    • Returns: string - all array elements joined with the specified separator
    • 1let words = ["Hello", "World", "JavaScript"];
      2console.log(words.join(" ")); // "Hello World JavaScript"
      3
      4// Join with different separators
      5let items = ["apple", "banana", "orange"];
      6console.log(items.join(", ")); // "apple, banana, orange"
      7console.log(items.join("-")); // "apple-banana-orange"
      8
      9// Join without separator
      10let chars = ["H", "e", "l", "l", "o"];
      11console.log(chars.join("")); // "Hello"
  19. 19match(regexp)
    • Used to: Find all matches of a regular expression pattern in a string
    • Syntax: str.match(regexp)
    • Returns: array - containing all matches, or null if no matches found
    • 1let str = "The rain in SPAIN stays mainly in the plain";
      2
      3// Regex Flags:
      4// g (global) - Find all matches rather than stopping after first match
      5// i (case insensitive) - Case doesn't matter when matching
      6// m (multiline) - ^ and $ match start/end of each line
      7// s (dotAll) - Dot (.) matches newline characters
      8// y (sticky) - Matches only from lastIndex
      9// u (unicode) - Enable unicode features
      10
      11// Using g flag to find all matches
      12console.log(str.match(/ain/g)); // ["ain", "ain", "ain"]
      13
      14// Using i flag for case-insensitive search
      15console.log(str.match(/spain/i)); // ["SPAIN"]
      16
      17// Using multiple flags (g and i)
      18console.log(str.match(/the/gi)); // ["The", "the"]
      19
      20// Using \w+ to match words, g flag for all matches
      21console.log(str.match(/\w+/g)); // ["The", "rain", "in", "SPAIN", ...]
  20. 20search(regexp)
    • Used to: Find the index of the first match of a regular expression
    • Syntax: str.search(regexp)
    • Returns: number - index of first match, or -1 if not found
    • 1let str = "Hello World! HELLO JavaScript!";
      2
      3// Basic search (case-sensitive)
      4console.log(str.search(/World/)); // 6
      5
      6// Using i flag for case-insensitive search
      7console.log(str.search(/hello/i)); // 0
      8
      9// Note: search() ignores g flag as it only returns first match
      10console.log(str.search(/hello/gi)); // 0
      11
      12// Pattern not found
      13console.log(str.search(/Python/)); // -1
  21. 21matchAll(regexp)
    • Used to: Get an iterator of all matches of a regular expression
    • Syntax: str.matchAll(regexp)
    • Returns: iterator - containing all match objects with additional information
    • 1let str = "Test1 test2 TEST3";
      2
      3// g flag is required for matchAll
      4// i flag for case-insensitive matching
      5let matches = [...str.matchAll(/test\d/gi)];
      6
      7// Each match object contains:
      8// - The full match
      9// - Index where match was found
      10// - Input string
      11// - Groups (if any)
      12console.log(matches);
      13// [
      14// ['Test1', index: 0, input: 'Test1 test2 TEST3', groups: undefined],
      15// ['test2', index: 6, input: 'Test1 test2 TEST3', groups: undefined],
      16// ['TEST3', index: 12, input: 'Test1 test2 TEST3', groups: undefined]
      17// ]
      18
      19// Using capture groups with g flag
      20let str2 = "2023-03-14 2024-01-01";
      21let dateMatches = [...str2.matchAll(/(\d{4})-(\d{2})-(\d{2})/g)];
      22dateMatches.forEach(match => {
      23 console.log(`Full date: ${match[0]}`);
      24 console.log(`Year: ${match[1]}, Month: ${match[2]}, Day: ${match[3]}`);
      25});

String Practice Questions

  1. 1How do you reverse a string in JavaScript?
  2. 2Write a function to check if a string is a palindrome.
  3. 3How do you find the first non-repeated character in a string?
  4. 4Write a function to count the occurrences of each character in a string.
  5. 5How do you check if two strings are anagrams?
  6. 6Write a function to capitalize the first letter of each word in a string.
  7. 7How do you remove duplicate characters from a string?
  8. 8Write a function to find the longest word in a string.
  9. 9How do you check if a string contains only numbers?
  10. 10Write a function to count the number of vowels and consonants in a string.

Special Characters

  1. 1Escaping Special Characters
    • \n - New line
    • \t - Tab
    • \' - Single quote (')
    • \" - Double quote (")
    • \` - Backtick
    • \\ - Backslash
    • \/ - Forward slash
    • \b - Backspace
    • \f - Form feed
    • \r - Carriage return
  2. 2Examples:
    1// Displaying quotes
    2let str1 = "He said \"Hello\""; // He said "Hello"
    3let str2 = 'It\'s a nice day'; // It's a nice day
    4let str3 = `Use \` for template`; // Use ` for template
    5
    6// Displaying paths
    7let windowsPath = "C:\\Program Files\\Apps"; // C:Program FilesApps
    8let unixPath = "/home/user/docs"; // /home/user/docs
    9
    10// Multiline strings
    11let multiline = "First line\nSecond line\nThird line";
    12/* Output:
    13First line
    14Second line
    15Third line */
    16
    17// Mixing quotes
    18let html = "<div class=\"main\">It\'s a \"quoted\" text</div>";
    19// <div class="main">It's a "quoted" text</div>
    20
    21// Unicode characters
    22let unicode = "\u00A9 2024"; // © 2024
    23let emoji = "\u{1F600}"; // 😀
  3. 3HTML Entity References
    • &quot; - For double quotes (")
    • &apos; - For single quotes (')
    • &amp; - For ampersand (&)
    • &lt; - For less than (<)
    • &gt; - For greater than (>)
    1// In HTML/JSX
    2<div>She said &quot;Hello&quot;</div> // She said "Hello"
    3<div>It&apos;s working</div> // It's working
    4<div>Price: 10&amp;20</div> // Price: 10&20
    5<div>1 &lt; 2 &amp;&amp; 3 &gt; 2</div> // 1 < 2 && 3 > 2

Share this article

Last updated: March 14, 2024

Join Our Community

Login to Join

© 2025 Saket Bhatnagar. All rights reserved.

    ☕