Skip to main content

Command Palette

Search for a command to run...

Master JavaScript String Methods & Polyfills with Examples

Updated
β€’4 min read
Master JavaScript String Methods & Polyfills with Examples

πŸ“Œ Introduction

Strings are one of the most commonly used data types in JavaScript. Whether you're building web apps or preparing for interviews, mastering string manipulation is essential.

In this blog, you’ll learn:

  • What string methods are

  • Why polyfills are important

  • How to implement string utilities from scratch

  • Common interview problems with solutions

  • How built-in methods work internally

This guide focuses on logic, clarity, and interview readiness.


πŸ”€ What Are String Methods?

String methods are built-in functions provided by JavaScript to manipulate text.

Examples:

let str = "Hello World";

str.length        // 11
str.toUpperCase() // "HELLO WORLD"
str.slice(0, 5)   // "Hello"
str.includes("World") // true

🧠 Conceptual Working

Most string methods internally:

  1. Traverse characters

  2. Perform comparisons or transformations

  3. Return a new string (strings are immutable)


❓ Why Developers Write Polyfills?

πŸ”§ Polyfill = Custom implementation of built-in methods

Reasons:

  • Older browsers may not support modern methods

  • Helps understand internal working

  • Important for JavaScript interviews


πŸ› οΈ Implementing String Polyfills

1. πŸ” includes() Polyfill

String.prototype.myIncludes = function(searchStr) {
  for (let i = 0; i <= this.length - searchStr.length; i++) {
    let match = true;

    for (let j = 0; j < searchStr.length; j++) {
      if (this[i + j] !== searchStr[j]) {
        match = false;
        break;
      }
    }

    if (match) return true;
  }
  return false;
};

Usage:

"hello".myIncludes("ell"); // true

2. βœ‚οΈ slice() Polyfill

String.prototype.mySlice = function(start, end) {
  let result = "";

  if (start < 0) start = this.length + start;
  if (end === undefined) end = this.length;

  for (let i = start; i < end; i++) {
    result += this[i];
  }

  return result;
};

3. πŸ”  toUpperCase() Polyfill

String.prototype.myToUpperCase = function() {
  let result = "";

  for (let char of this) {
    if (char >= 'a' && char <= 'z') {
      result += String.fromCharCode(char.charCodeAt(0) - 32);
    } else {
      result += char;
    }
  }

  return result;
};

πŸ” String Processing Flow (Concept)

Input String β†’ Traverse Characters β†’ Apply Logic β†’ Build Result β†’ Return Output

🧠 Common Interview String Problems


1. πŸ”„ Reverse a String

function reverseString(str) {
  let result = "";

  for (let i = str.length - 1; i >= 0; i--) {
    result += str[i];
  }

  return result;
}

2. πŸ” Check Palindrome

function isPalindrome(str) {
  let reversed = str.split("").reverse().join("");
  return str === reversed;
}

πŸ‘‰ Optimized (without extra space):

function isPalindrome(str) {
  let left = 0, right = str.length - 1;

  while (left < right) {
    if (str[left] !== str[right]) return false;
    left++;
    right--;
  }

  return true;
}

3. πŸ”’ Count Character Frequency

function charFrequency(str) {
  let map = {};

  for (let char of str) {
    map[char] = (map[char] || 0) + 1;
  }

  return map;
}

4. πŸ” First Non-Repeating Character

function firstUniqueChar(str) {
  let map = {};

  for (let char of str) {
    map[char] = (map[char] || 0) + 1;
  }

  for (let char of str) {
    if (map[char] === 1) return char;
  }

  return null;
}

5. πŸ”‘ Anagram Check

function isAnagram(str1, str2) {
  if (str1.length !== str2.length) return false;

  let count = {};

  for (let char of str1) {
    count[char] = (count[char] || 0) + 1;
  }

  for (let char of str2) {
    if (!count[char]) return false;
    count[char]--;
  }

  return true;
}

βš™οΈ Understanding Built-in Behavior

Example: includes()

Internally:

  • It checks substring existence

  • Uses sliding window technique

  • Compares characters sequentially

Example: slice()

  • Handles negative indexes

  • Returns a new substring

  • Does not modify original string


πŸ’‘ Interview Tips

  • Don’t just memorize methods β€” understand logic

  • Practice writing polyfills from scratch

  • Focus on edge cases:

    • Empty strings

    • Case sensitivity

    • Special characters


πŸ“Š Polyfill Behavior Representation

Built-in Method Call
        ↓
Check Input Validity
        ↓
Loop Through String
        ↓
Apply Logic (compare/transform)
        ↓
Return Result

🎯 Final Thoughts

Mastering string methods and polyfills gives you:

βœ… Strong JavaScript fundamentals βœ… Confidence in interviews βœ… Ability to solve complex problems

If you can implement these from scratch, you're already ahead of many candidates.


πŸš€ Practice Challenge

Try implementing:

  • trim() polyfill

  • replace() polyfill

  • Longest substring without repeating characters


More from this blog

Dev Blog by Vishal

36 posts