- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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' ]
Advertisements