Skip to main content

Command Palette

Search for a command to run...

String Polyfills and Common Methods in JavaScript

Build core understanding of string methods and implement them from scratch

Updated
•2 min read•View as Markdown

When we start working with JS, string look simple. Just text, right? But in real world development and interviews, strings become one of the most important and frequently tested topics. In this blog, we'll break down string methods, understand polyfills and implement some common utilities in a clean and simple way.


What are String Methods?

String methods are built-in functions provided by JavaScript to manipulate text.
Some commonly used ones:

  • toUpperCase()

  • toLowerCase()

  • slice()

  • substring()

  • includes()

  • split()

  • trim()

Example:

const name = "Elon";

console.log(name.toUpperCase()); // ELON
console.log(name.includes("on")); // true

What's actually happening?

Behind the scenes:

  • Strings are primitive values (basic immutable data type), but JavaScript temporarily wraps them in a String object

  • That’s why we can call methods on them


Why Developers Write Polyfills

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

Why do we need it?

  1. Older browser may not support modern methods

  2. Helps understand how JavaScript works internally

  3. Commonly asked in interviews to test problem solving.


Implementing Simple String Utilities (Polyfills)

includes() Polyfill

Problem:

Check if a string contains another string.

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

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

        if (found) return true;
    }

    return false;
};

// Usage
console.log("hello world".myIncludes("world")); // true

Logic:

  • Loop through main string

  • Compare character by character

  • Return true if full match found


trim() Polyfill

Problem:

Remove spaces from start and end.

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

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

    let result = "";

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

    return result;
};

// Usage
console.log("   hello   ".myTrim()); // "hello"

Logic:

  • Move start pointer forward

  • Move end pointer backward

  • Extract middle part


1 views