Skip to main content

Command Palette

Search for a command to run...

String Polyfills and Common Interview Methods in JavaScript

Updated
•3 min read•View as Markdown

What string methods are?

String methods are built-in functions provided by JavaScript to manipulate and work with strings.

Common Examples:

const str = "hello world";

str.toUpperCase();     // "HELLO WORLD"
str.includes("world"); // true
str.slice(0, 5);       // "hello"
str.trim();            // removes whitespace
str.split(" ");        // ["hello", "world"]

Why developers write polyfills?

  1. Browser Compatibility

    • Older browsers may not support modern methods like includes, startsWith
  2. Understanding Internals

    • Helps you deeply understand how JS works under the hood
  3. Interview Preparation

    • Frequently asked in frontend/backend interviews

Example: Polyfill for includes()

String.prototype.myIncludes = function (search, start = 0) {
    if (start + search.length > this.length) return false;

    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;
  };

Implementing Simple String Utilities

These are often asked in interviews to test logic-building skills.

1. Reverse a String

function reverseString(str) {
  return str.split("").reverse().join("");
}

2. Check Palindrome

function isPalindrome(str) {
  const cleaned = str.toLowerCase().replace(/[^a-z0-9]/g, "");
  return cleaned === cleaned.split("").reverse().join("");
}

3. Count Characters

function charCount(str) {
  const map = {};

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

  return map;
}

4. Capitalize First Letter

function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

Common Interview String Problems

These are high-frequency interview questions:

1. Longest Substring Without Repeating Characters

  • Uses sliding window technique

  • Tests optimization skills


2. Anagram Check

function isAnagram(s1, s2) {
  if (s1.length !== s2.length) return false;

  return s1.split("").sort().join("") === s2.split("").sort().join("");
}

3. First Non-Repeating Character

function firstUniqueChar(str) {
  const 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;
}

4. 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;
}