Skip to main content

Command Palette

Search for a command to run...

String Polyfills and Common Interview Methods in JavaScript

Updated
6 min read
String Polyfills and Common Interview Methods in JavaScript
D
CS student focused on backend & OS fundamentals. Building real projects and sharing practical learning.

String

string is just a sequencce of character

properties

  1. Strings are immutable

  2. Strings behave like arrays (but they’re NOT arrays)

  3. Strings are objects under the hood

way to create string

let a = "hello";      // double quotes
let b = 'hello';      // single quotes
let c = `hello`;      // template literal

String Method

string method are built in funtion provided by JS to perform ioerationnn on string

simply pre written logic thst saves from writting commo operatio againn and again

example

  • finding something → indexOf(), includes()

  • extracting → slice(), substring()

  • modifying → replace(), toUpperCase()

  • splitting → split()

note string method do not modify the original dtring because thay are immutable

types of method

instead of going onn each method lets categorised them

  1. Searching Methods
  • indexof()
let str = "javascript";

console.log(str.indexOf("script")); // 4
console.log(str.indexOf("java"));   // 0
console.log(str.indexOf("xyz"));    // -1
  • include()
let str = "javascript";

console.log(str.includes("script")); // true
console.log(str.includes("java"));   // true
console.log(str.includes("xyz"));    // false

used to find character or substring

2 . Extraacting Method

  • slice()
let str = "javascript";

console.log(str.slice(0, 4));  // "java"
console.log(str.slice(4));     // "script"
console.log(str.slice(-3));    // "ipt"
  • substring()

Used to get part of a string

let str = "javascript";

console.log(str.substring(0, 4));   // "java"
console.log(str.substring(4));      // "script"
console.log(str.substring(-2, 4));  // "java"

3. Transforming methods

  • toUpperCase()
let str = "hello";

console.log(str.toUpperCase()); // "HELLO"
  • toLowerCase()
let str = "HELLO";

console.log(str.toLowerCase()); // "hello"
  • trim()
let str = "   hello   ";

console.log(str.trim()); // "hello"

Used to change format

Why developers write polyfills

polyfill

It is a piece of code that add a feture to javascript that is not availiable in the environment

in simlly if Js doesnot suppport something you write your own version of it

example

if (!String.prototype.includes) {
  String.prototype.includes = function(search) {
    return this.indexOf(search) !== -1;
  };
}

Now:

"hello".includes("ell"); // works even if browser didn’t support it

What’s actually happening here

under the hood:

  • if (!String.prototype.includes)

    → check if method already exists

  • If NOT → define it

  • Attach to String.prototype

    → so all strings can use it

a polyfill is like a building your own tool when the toolbox doesn't have it

Implementing simple string utilities

Polyfill for include()

so what we are doing is

  • loop through string

  • compare substring at each position

  • return true if match found

String.prototype.myIncludes = function(search) {
  for (let i = 0; i <= this.length - search.length; i++) {
    if (this.substring(i, i + search.length) === search) {
      return true;
    }
  }
  return false;
};

usage

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

Polyfill for indexOf()

  • Same as includes

  • Instead of true/false → return index

String.prototype.myIndexOf = function(search) {
  for (let i = 0; i <= this.length - search.length; i++) {
    if (this.substring(i, i + search.length) === search) {
      return i;
    }
  }
  return -1;
};

Usage:

"hello".myIndexOf("ll"); // 2

Polyfill for slice()

This one exposes whether you actually understand indexing.

  • Take start and end

  • Handle negative index

  • Build new string

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

  start = start < 0 ? len + start : start;
  end = end === undefined ? len : end;
  end = end < 0 ? len + end : end;

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

  return result;
};

Usage:

"javascript".mySlice(0, 4);  // "java"
"javascript".mySlice(-3);    // "ipt"

Polyfill for split()

important one

  • Traverse string

  • Break when separator found

  • Push into array

String.prototype.mySplit = function(separator) {
  let result = [];
  let current = "";

  for (let i = 0; i < this.length; i++) {
    if (this[i] === separator) {
      result.push(current);
      current = "";
    } else {
      current += this[i];
    }
  }

  result.push(current);
  return result;
};

Usage:

"apple,banana,mango".mySplit(",");
// ["apple", "banana", "mango"

Interview question

here are some list of tpic that is most frequently asked topic

1 . Reverse a strinng

function reverse(str) {
  let res = "";
  for (let i = str.length - 1; i >= 0; i--) {
    res += str[i];
  }
  return res;
}

2 . Palinndrome Check

Check if string reads same forward & backward

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

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

  return true;
}

pattrern - two pointer

3 . anagram Check

same character different order

function isAnagram(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;
}

hashing / frequenccy count

4 . First non-repeating character

function firstUnique(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;
}

pattern - count first , then find

5 . Longest substrign without repeating characcter

function longestUnique(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;
}

pattern - sliding window

Importance of Understanding Built in behaviour

Most developers rely on built-in methods without understanding them.

That creates problems:

  • we could make mistakes in edge cases

  • we can’t debug efficiently

Example:

"hello".slice(-2);     // "lo"
"hello".substring(-2); // "hello"

Same purpose, different behavior.

Understanding built-ins means:

  • Knowing the logic behind them

  • Handling edge cases

  • Understanding time complexity