Skip to main content

Command Palette

Search for a command to run...

String Polyfills and Common Interview Methods in JavaScript

Updated
•5 min read•View as Markdown

Introduction

Strings are one of the most frequently used data types in JavaScript. They are used to handle user input, display content, manipulate data, and perform transformations. JavaScript provides a wide range of built-in string methods, but understanding how these methods work internally is crucial for mastering the language.

In technical interviews, developers are often asked to implement these methods manually. This is where polyfills become important. This document explores string methods, the need for polyfills, implementation of common utilities, and frequently asked interview problems.

What String Methods Are

String methods are built-in functions that operate on string values. Since strings in JavaScript are immutable, these methods do not modify the original string. Instead, they return new strings or values.

Categories of String Methods

Inspection Methods

These methods analyze the string and return information.

Examples:

  • length

  • charAt()

  • indexOf()

  • includes()

  • startsWith()

  • endsWith()

Extraction Methods

These methods extract parts of a string.

Examples:

  • slice()

  • substring()

Transformation Methods

These methods return modified versions of strings.

Examples:

  • toUpperCase()

  • toLowerCase()

  • trim()

  • replace()

  • split()

Search Methods

These methods locate patterns within strings.

Examples:

  • search()

  • match()

Conceptual Behavior

Why Developers Write Polyfills

A polyfill is a custom implementation of a built-in method.

Reasons for Writing Polyfills

Understanding Internal Logic

Recreating methods helps understand how they work step by step.

Handling Edge Cases

Polyfills require handling invalid inputs, boundaries, and type conversions.

Interview Preparation

Interviewers often test:

  • Logical thinking

  • Knowledge of JavaScript fundamentals

  • Ability to handle edge cases

Consistency Across Environments

In older environments, some methods may not exist.

Implementing Simple String Utilities

Custom charAt Implementation

String.prototype.customCharAt = function(index) {
  let position = Math.floor(index) || 0;

  if (position < 0 || position >= this.length) {
    return "";
  }

  return this[position];
};

console.log("world".customCharAt(2)); // "r"

Custom includes Implementation

String.prototype.customIncludes = function(search, position) {
  let start = position || 0;

  for (let i = start; i <= this.length - search.length; i++) {
    let match = true;

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

    if (match) return true;
  }

  return false;
};

console.log("javascript".customIncludes("script")); // true

Custom startsWith Implementation

String.prototype.customStartsWith = function(search, position) {
  let start = position || 0;

  for (let i = 0; i < search.length; i++) {
    if (this[start + i] !== search[i]) {
      return false;
    }
  }

  return true;
};

console.log("developer".customStartsWith("dev")); // true

Custom trim Implementation

String.prototype.customTrim = function() {
  let start = 0;
  let end = this.length - 1;

  while (this[start] === " ") start++;
  while (this[end] === " ") end--;

  return this.slice(start, end + 1);
};

console.log("  code  ".customTrim()); // "code"

Custom repeat Implementation

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

  for (let i = 0; i < count; i++) {
    result += this;
  }

  return result;
};

console.log("ab".customRepeat(3)); // "ababab"

Custom padStart Implementation

String.prototype.customPadStart = function(targetLength, padString) {
  let padding = "";

  while (padding.length < targetLength - this.length) {
    padding += padString;
  }

  return padding.slice(0, targetLength - this.length) + this;
};

console.log("7".customPadStart(3, "0")); // "007"

String Processing Flow

Common Interview String Problems

Reverse a String

Using Loop

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

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

  return result;
}

console.log(reverse("code")); // "edoc"

Check for Palindrome

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

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

  return true;
}

console.log(checkPalindrome("madam")); // true

First Non-Repeating Character

function firstUnique(str) {
  let count = {};

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

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

  return null;
}

console.log(firstUnique("swiss")); // "w"

Longest Substring Without Repeating Characters

function longestUniqueSubstring(str) {
  let set = new Set();
  let left = 0;
  let max = 0;

  for (let right = 0; right < str.length; right++) {
    while (set.has(str[right])) {
      set.delete(str[left]);
      left++;
    }

    set.add(str[right]);
    max = Math.max(max, right - left + 1);
  }

  return max;
}

console.log(longestUniqueSubstring("abcabcbb")); // 3

String Compression

function compress(str) {
  let result = "";
  let count = 1;

  for (let i = 0; i < str.length; i++) {
    if (str[i] === str[i + 1]) {
      count++;
    } else {
      result += str[i] + count;
      count = 1;
    }
  }

  return result.length < str.length ? result : str;
}

console.log(compress("aaabbc")); // "a3b2c1"

Anagram Check

function checkAnagram(a, b) {
  if (a.length !== b.length) return false;

  let map = {};

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

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

  return true;
}

console.log(checkAnagram("listen", "silent")); // true

Polyfill Behavior Representation

Importance of Understanding Built-in Behavior

Deeper Understanding

Writing polyfills forces developers to understand internal working.

Improved Problem Solving

Breaking down methods improves logical thinking.

Strong Fundamentals

Covers:

  • Prototypes

  • Loops

  • Type handling

  • Edge cases

Interview Readiness

Most technical interviews include:

  • String manipulation problems

  • Custom implementation tasks

Performance Awareness

Helps in writing optimized and efficient code.

Conclusion

String polyfills and related interview problems are essential for mastering JavaScript fundamentals. They bridge the gap between using built-in methods and understanding their internal behavior.

By practicing these implementations and problems, developers gain stronger problem-solving skills, deeper language understanding, and better preparation for real-world coding challenges and technical interviews.