
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
String function to replace nth occurrence of a character in a string JavaScript
We are required to write a function removeStr() that lives on String.prototype object and takes in a string str, a character char and a number n.
The function should remove the nth appearance of char from str.
Let’s write the code for this −
const str = 'aaaaaa'; const subStr = 'a'; const num = 6; removeStr = function(subStr, num){ if(!this.includes(subStr)){ return -1; } let start = 0, end = subStr.length; let occurences = 0; for(; ;end < this.length){ if(this.substring(start, end) === subStr){ occurences++; }; if(occurences === num){ return this.substring(0, start) + this.substring(end, this.length); }; end++; start++; } return -1; } String.prototype.removeStr = removeStr; console.log(str.removeStr(subStr, num));
Output for this code in the console will be −
aaaaa
- Related Articles
- Create a polyfill to replace nth occurrence of a string JavaScript
- C program to replace all occurrence of a character in a string
- JavaScript - Writing a string function to replace the kth appearance of a character
- Insert a character at nth position in string in JavaScript
- Python - Replace duplicate Occurrence in String
- Replace first occurrence of a character in Java
- C Program to find minimum occurrence of character in a string
- C Program to find maximum occurrence of character in a string
- How to find the nth occurrence of substring in a string in Python?
- C# Program to find number of occurrence of a character in a String
- How to count the occurrence of a specific string in a string in JavaScript
- Finding the last occurrence of a character in a String in Java
- Replace Character in a String in Java without using replace() method
- Replace words of a string - JavaScript
- Removing nth character from a string in Python program

Advertisements