
- 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
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 Articles
- 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
- Implementing Math function and return m^n in JavaScript
- Create a custom toLowerCase() function in JavaScript
- What is function prototype in C language
- Accessing variables in a constructor function using a prototype method with JavaScript?
- How to define custom sort function in JavaScript?
- Writing a custom URL shortener function in JavaScript
- Search a string in Matrix Using Split function in Java
- JavaScript function that lives on the prototype object of the Array class
- Adding a function for swapping cases to the prototype object of strings - JavaScript
- Custom len() Function In Python
- Number prime test in JavaScript by creating a custom function?
- Function to decode a string in JavaScript

Advertisements