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
JavaScript - Writing a string function to replace the kth appearance of a character
Let's say, we are required to write a String.prototype function that takes in three arguments.
- First argument is string that should be searched for substrings
- Second argument is the string, the occurrence of which String to be removed
- Third argument is a Number say n, nth occurrence of substring to be removed from string.
The function should return the new string if the removal of the subStr from the string was successful, otherwise it should return -1 in all cases.
Example
Following is the code ?
const str = 'jkdsttjkdsre';
const subStr = 'jk';
const num = 2;
removeStr = function(subStr, num) {
if (!this.includes(subStr)) {
return -1;
}
let start = 0, end = subStr.length;
let occurences = 0;
for (; end < this.length; end++, start++) {
if (this.substring(start, end) === subStr) {
occurences++;
}
if (occurences === num) {
return this.substring(0, start) + this.substring(end, this.length);
}
}
return -1; // Not enough occurrences found
}
String.prototype.removeStr = removeStr;
console.log(str.removeStr(subStr, num));
jkdsttdsre
How It Works
This function firstly checks: If there's not even a single occurrence of subStr then we should exit out and return -1
Then it uses the sliding window algorithm to record the number of occurrences of subStr in string (the size of window being equal to length of subStr)
Initially, we start from leftmost window then we keep sliding our window till the end of window reaches the end of original string. If in our way, the count of occurrences equals the required occurrence, we trim that occurrence from the string and return the new string thus obtained.
If we iterate through the whole string, it means there are not enough occurrences of subStr in string and in that case we should return -1 and exit the function.
Lastly, we add the removeStr property to String.prototype so that we can call it as a string function.
Another Example
Let's test with different parameters to see how the function behaves:
const testStr = 'hello world hello universe hello';
// Remove 2nd occurrence of 'hello'
console.log(testStr.removeStr('hello', 2));
// Try to remove 5th occurrence (doesn't exist)
console.log(testStr.removeStr('hello', 5));
// Remove substring that doesn't exist
console.log(testStr.removeStr('xyz', 1));
hello world universe hello -1 -1
Conclusion
This custom String prototype function efficiently removes the kth occurrence of a substring using a sliding window approach. It returns the modified string on success or -1 when the specified occurrence doesn't exist.
