Skip to main content

Command Palette

Search for a command to run...

String Polyfills and Common Interview Methods in JavaScript

Understand how built-in string methods work under the hood - and write them yourself like a pro developer.

Updated
7 min read
String Polyfills and Common Interview
Methods in JavaScript

What are String Methods?

A string method is a built-in function that JavaScript gives you to work with text. Think of strings as sequences of characters — like beads on a necklace. String methods let you count the beads, find a specific bead, replace one bead with another, or rearrange them.

For example, when you have a name like "hello world", you can instantly convert it to uppercase with .toUpperCase(), or find where a word starts with .indexOf(), or cut out a part of it with .slice().

Simple way to think about it: A string method is like a tool in a toolbox. The string is the material you're working on, and the method is the tool that shapes it.

Method What it does Example
.toUpperCase() Converts all letters to uppercase "hello" → "HELLO"
.toLowerCase() Converts all letters to lowercase "HELLO" → "hello"
.trim() Removes spaces from both ends " hi " → "hi"
.includes() Checks if a word exists inside "hello".includes("ell") → true
.slice() Cuts out a part of the string "hello".slice(1,3) → "el"
.split() Breaks string into an array "a,b,c".split(",") → ["a","b","c"]
.repeat() Repeats the string N times "ha".repeat(3) → "hahaha"
.startsWith() Checks if it begins with a value "hello".startsWith("he") → true

Why Do Developers Write Polyfills?

A polyfill is a piece of code you write yourself to replicate a built-in feature — usually because that feature does not exist in older browsers, or because you want to deeply understand how it works.

Imagine JavaScript's .includes() method was added in ES6 (2015). If your user is running Internet Explorer 11, that method simply does not exist. A polyfill fills the gap — it checks if the feature is missing, and if so, adds your own version of it.

Interview Insight: Interviewers often ask you to "implement your own version of .includes()" not because you'll do it in real life, but to test if you understand loops, indexing, and how the method works conceptually.

The Three Reasons to Write Polyfills

  1. Browser compatibility — older environments don't have newer methods.

  2. Interview preparation — it shows you truly understand the logic, not just the syntax.

  3. Learning deeply — when you write something from scratch, you understand it forever.

Important: A polyfill should behave exactly like the original method — same input, same output, same edge cases. That's what makes it reliable.


String Processing Flow

Here's how JavaScript processes a string method call from the moment you write it to when you get a result back:


Implementing Simple String Utilities

Let's write our own versions of the most popular string methods. For each one, we'll first understand the concept, then write the code.

1. Custom includes()

The original .includes() checks if a smaller string exists inside a bigger string. The idea: slide a window of the same length as the search word across the string, and at each position check if the characters match.

JavaScript — Custom includes()

// Attach our custom method to String.prototype
if (!String.prototype.myIncludes) {
  String.prototype.myIncludes = function(searchStr) {

    // Loop through each position in the original string
    for (let i = 0; i <= this.length - searchStr.length; i++) {
      let match = true;

      // Check each character of the search word
      for (let j = 0; j < searchStr.length; j++) {
        if (this[i + j] !== searchStr[j]) {
          match = false;
          break;
        }
      }

      if (match) return true;
    }

    return false;
  };
}

// Test it
console.log("hello world".myIncludes("world")); // true
console.log("hello world".myIncludes("xyz"));   // false

2. Custom trim()

The .trim() method removes whitespace (spaces, tabs) from both the start and end of a string. The logic: find the first non-space character and the last non-space character, then return everything in between.

JavaScript — Custom trim()

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

  // Move start forward while we see spaces
  while (start <= end && this[start] === ' ') {
    start++;
  }

  // Move end backward while we see spaces
  while (end >= start && this[end] === ' ') {
    end--;
  }

  // Return only the middle part
  return this.slice(start, end + 1);
};

// Test it
console.log("  hello  ".myTrim()); // "hello"
console.log("  hi".myTrim());      // "hi"

3. Custom repeat()

The .repeat(n) method returns the string copied n times. Simple logic: start with an empty result, and keep adding the string to itself n times using a loop.

String.prototype.myRepeat = function(n) {
  if (n < 0) throw new RangeError("Count must be >= 0");
  if (n === 0) return "";

  let result = "";
  for (let i = 0; i < n; i++) {
    result += this;
  }
  return result;
};

// Test it
console.log("ha".myRepeat(3)); // "hahaha"
console.log("*".myRepeat(5));  // "*****"

Custom startsWith()

The .startsWith(word) method checks if the string begins with a given value. The trick is simple — compare the first few characters of the string with the search word, one by one.

JavaScript — Custom startsWith()

String.prototype.myStartsWith = function(searchStr) {
  // If search is longer than string, it can't match
  if (searchStr.length > this.length) return false;

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

  return true;
};

// Test it
console.log("hello".myStartsWith("he"));  // true
console.log("hello".myStartsWith("lo"));  // false

How a Polyfill Works (Under the Hood)

Here's the decision flow that happens every time you call a string method — and where your polyfill steps in when the built-in version is missing:


Common Interview String Problems

These are the string problems that show up again and again in JavaScript interviews. For each one, the trick is to understand the logic before you touch the keyboard.

Reverse a String

Write a function that reverses a string without using the built-in .reverse() method.

function reverseString(str) {
  let result = "";
  // Walk from the end to the beginning
  for (let i = str.length - 1; i >= 0; i--) {
    result += str[i];
  }
  return result;
}

console.log(reverseString("hello")); // "olleh"
console.log(reverseString("abcd"));  // "dcba"

Check if a String is a Palindrome

A palindrome reads the same forward and backward (e.g. "racecar"). Check if a given string is one.

function isPalindrome(str) {
  // Use two pointers — one at start, one at end
  let left = 0;
  let right = str.length - 1;

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

console.log(isPalindrome("racecar")); // true
console.log(isPalindrome("hello"));   // false

Count Vowels in a String

Count how many vowels (a, e, i, o, u) exist in a given string.

function countVowels(str) {
  const vowels = "aeiouAEIOU";
  let count = 0;

  for (let char of str) {
    if (vowels.includes(char)) {
      count++;
    }
  }
  return count;
}

console.log(countVowels("hello world")); // 3
console.log(countVowels("JavaScript"));  // 3

Find the First Non-Repeating Character

Given a string, find the first character that appears only once.

function firstUnique(str) {
  // Step 1: Count how many times each character appears
  const count = {};

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

  // Step 2: Find the first one with count = 1
  for (let char of str) {
    if (count[char] === 1) return char;
  }

  return null;
}

console.log(firstUnique("aabbcde")); // "c"
console.log(firstUnique("aabb"));    // null

Happy coding!