

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Implementing custom function like String.prototype.split() function in JavaScript
Problem
We are required to write a JavaScript function that lives on the prototype object of the String class.
It should take in a string separator as the only argument (although the original split function takes two arguments). And our function should return an array of parts of the string separated and split by the separator.
Example
Following is the code −
const str = 'this is some string'; String.prototype.customSplit = (sep = '') => { const res = []; let temp = ''; for(let i = 0; i < str.length; i++){ const el = str[i]; if(el === sep || sep === '' && temp){ res.push(temp); temp = ''; }; if(el !== sep){ temp += el; } }; if(temp){ res.push(temp); temp = ''; }; return res; }; console.log(str.customSplit(' '));
Output
[ 'this', 'is', 'some', 'string' ]
- Related Questions & Answers
- Implementing a custom function like Array.prototype.filter() function in JavaScript
- Implementing the Array.prototype.lastIndexOf() function in JavaScript
- Importance of function prototype in C
- What is function prototype in C language
- Implementing Math function and return m^n in JavaScript
- Create a custom toLowerCase() function in JavaScript
- How to define custom sort function in JavaScript?
- Writing a custom URL shortener function in JavaScript
- Accessing variables in a constructor function using a prototype method with JavaScript?
- Custom len() Function In Python
- JavaScript function that lives on the prototype object of the Array class
- Search a string in Matrix Using Split function in Java
- Adding a function for swapping cases to the prototype object of strings - JavaScript
- Number prime test in JavaScript by creating a custom function?
- Custom list split in Python
Advertisements