Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Create a polyfill to replace nth occurrence of a string JavaScript
A polyfill is a piece of code that provides functionality that isn't natively supported. In this tutorial, we'll create a polyfill to remove the nth occurrence of a substring from a string in JavaScript.
Problem Statement
We need to create a polyfill function removeStr() that extends the String prototype. The function should:
subStr ? the substring whose nth occurrence needs to be removed
num ? the occurrence number to remove (1st, 2nd, 3rd, etc.)
Return the modified string if successful, or
-1if the nth occurrence doesn't exist
For example, removing the 3rd occurrence of "dr" from "drsfgdrrtdr" should return "drsfgdrrt".
Implementation
const removeStr = function(subStr, num) {
// Check if substring exists in the string
if (!this.includes(subStr)) {
return -1;
}
let start = 0, end = subStr.length;
let occurrences = 0;
// Sliding window approach to find occurrences
for (; end <= this.length; start++, end++) {
if (this.substring(start, end) === subStr) {
occurrences++;
// Found the nth occurrence
if (occurrences === num) {
return this.substring(0, start) + this.substring(end, this.length);
}
}
}
// nth occurrence not found
return -1;
};
// Add to String prototype
String.prototype.removeStr = removeStr;
// Test the polyfill
const str = 'drsfgdrrtdr';
console.log("Original string:", str);
console.log("Remove 2nd 'dr':", str.removeStr('dr', 2));
console.log("Remove 3rd 'dr':", str.removeStr('dr', 3));
console.log("Remove 4th 'dr':", str.removeStr('dr', 4)); // Should return -1
Original string: drsfgdrrtdr Remove 2nd 'dr': drsfgrtdr Remove 3rd 'dr': drsfgdrrt Remove 4th 'dr': -1
How It Works
The algorithm uses a sliding window technique:
Initial Check: Verifies if the substring exists at all using
includes()Sliding Window: Creates a window of size equal to the substring length
Occurrence Counting: Slides the window character by character, counting matches
String Reconstruction: When the nth occurrence is found, concatenates the parts before and after it
Prototype Extension: Adds the function to
String.prototypefor easy usage
Additional Examples
// Test with different scenarios
console.log("'hello world hello'".removeStr('hello', 1)); // " world hello"
console.log("'hello world hello'".removeStr('hello', 2)); // "hello world "
console.log("'abcabcabc'".removeStr('abc', 2)); // "abcabc"
console.log("'test'".removeStr('xyz', 1)); // -1 (not found)
world hello hello world abcabc -1
Conclusion
This polyfill demonstrates how to extend JavaScript's String prototype with custom functionality. The sliding window approach efficiently finds and removes the nth occurrence of any substring, making it a useful utility for string manipulation tasks.
